【问题标题】:Quasar Framework: Method inside watcher is not recognizedQuasar Framework:观察者内部的方法无法识别
【发布时间】:2017-12-06 09:08:41
【问题描述】:

我正在尝试在 Quasar-Framework 应用程序中使用观察器,但观察器内部的方法未被识别为方法。

 data () {
   return {
     education: { degree:'test' },
     type: 2
   }
 },
 watch: {
   type: (newType) => {
     if (newType === 1) {
       this.removeDegree()
     }
   }
 },
 methods: {
   removeDegree () {
     this.education.degree = ''
   }
 }

我希望 removeDegree 会被调用,但是会抛出警告和错误,表明 removeDegree 不是函数。

参考:VueJS: Watchers

解决方案: 使用@docnoe 建议的简写 es6 语法

watch: {
  type (newType) {
    if (newType === 1) {
      this.removeDegree()
    }
  }
},
...

【问题讨论】:

  • 首先 data 对象定义不正确 - 它应该是返回对象的函数。接下来,我认为你的 watcher 中的箭头函数会导致问题,所以 this 没有绑定到正确的上下文。
  • @BelminBedak 对不起。我已经更正了返回的数据,因为它不是那样的。我已经检查了 docnoe 的建议,是的,你是正确的,应该不再有箭头了。我正在发布对我有用的解决方案。

标签: cordova vue.js quasar-framework


【解决方案1】:

@Belmin Bedak 已经在他的评论中回答了这个问题:“type”上的手表使用的箭头功能破坏了对“this”的引用。请改用普通函数。

固定代码:

new Vue({
  el: "#app",
  data() {
    return {
      education: { degree: "test" },
      type: 2,
      type2: 2,
      type3: 3
    };
  },
  watch: {
    // shorthand es6 syntax
    type(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // this is also valid
    type2: function(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // or using a handler
    type3: {
      handler(newType) {
        if (newType === 1) {
          this.removeDegree();
        }
      },
      // other watch options
      immediate: true
    }
  },
  methods: {
    removeDegree() {
      this.education.degree = "";
    }
  }
});

Codepen

【讨论】:

  • 简写 es6 语法对我来说 100% 有效。谢谢@docnoe。您对 Belmin Bedak 的回答也是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多