Skip to content

watch和computed使用箭头函数时,不能用this

在watch和computed中,使用箭头函数的时候,在方法里不要使用this,因为this指向不是vue实例

错误:

vue
computed: {
  tdata: () => {
    this.ttest()
    return ''
  }
}

正确:

vue
computed: {
  tdata() {
    this.ttest()
    return ''
  }
}



computed: {
  tdata: function () {
    this.ttest()
    return ''
  }
}

不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.updateAutocomplete 将是 undefined。

如有转载或 CV 的请标注本站原文地址