【问题标题】:Vue.js method is undefined when called [duplicate]调用时未定义 Vue.js 方法[重复]
【发布时间】:2018-07-28 22:34:38
【问题描述】:

我正在尝试使用 Browserify 使用 Vue 构建一个 chrome 扩展,在我的组件文件中我试图从 mounted 方法调用组件的一个方法,称为 animateBackground 但在控制台上它给出了平均错误,如何调用组件的数据和方法? 代码:

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
  }
};

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    this里面的回调不是你的vue实例你可以console.log看看它是什么。有很多解决方法。其中一个你可以使用 es6 箭头函数语法,你也可以声明一个新变量并在回调外部分配this 然后用变量调用它,这里是一个例子:

    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
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-31
      • 2020-09-19
      • 2021-03-05
      • 2017-09-12
      • 2019-11-04
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多