-1

I am trying to build a chrome extension with Vue using Browserify, in my component file I am trying to call from the mounted method a method of the component called animateBackground but on the console it gives mean error, how do I call data and methods of the component? The code:

export default {
      name: "app",
      data() {
        return {
          'message': "thgdfseaw"
        }
      },
      mounted() {
        chrome.storage.local.get("bingImage", function(output) {
          if (output != undefined || output != null) {
            console.log(this.message);
            this.animateBackground(output.bingImage.base64);
          }});
  },
  methods: {
    animateBackground(base64) {
      $("#app").animate({ opacity: 0 }, "slow", function() {
        $(this)
          .css({ "background-image": "url(" + base64 + ")" })
          .animate({ opacity: 1 });
      });
    }
  },
  components: {
    AppSection
  }
};

This is what I see on chrome console

MatteoP
  • 46
  • 2
  • 10

1 Answers1

1

this inside the callback is not your vue instance you can console.log it to see what is it. there is many workaround for this. one of which you can use es6 arrow function syntax, also you can declare a new variable and assign this outside the callback then call it with the variable, here is an example:

export default {
      name: "app",
      data() {
        return {
          'message': "thgdfseaw"
        }
      },
      mounted() {
        var _vue = this // << here
        chrome.storage.local.get("bingImage", function(output) {
          if (output != undefined || output != null) {
            console.log(_vue.message); // << then access it like this
            _vue.animateBackground(output.bingImage.base64);
          }});
  },
  methods: {
    animateBackground(base64) {
      $("#app").animate({ opacity: 0 }, "slow", function() {
        $(this)
          .css({ "background-image": "url(" + base64 + ")" })
          .animate({ opacity: 1 });
      });
    }
  },
  components: {
    AppSection
  }
};
Mohd_PH
  • 1,590
  • 12
  • 19