watch,computed中箭头函数中没有this?

2020-03-18  本文已影响0人  深情的白杨

1、watch中的函数

feedbackRadio: {
     handler: (val)  => {
         if (val === '1' && this.reviewMsg) {
              this.reviewMsg.errorType = null; // 访问不到this,报错
         }
     },
     immediate: true
}

immediate为true是为了初始值的时候就开始监听

解决方案 替换箭头函数为普通函数即可

2、computed中的get与set函数

computed: {
  handleRes: {
      get: function () {
        return '';
      },
      set: function(val) {}
  }
}

get与set函数的定义不能使用箭头函数,this的值是undefined,set函数在设置handleRes的时候触发,val是被新设定的值,get函数是返回计算后的结果,返回的结果在页面中渲染。

上一篇 下一篇

猜你喜欢

热点阅读