VueJS:为什么“this”未定义?

新手上路,请多包涵

我正在使用 Vue.js 创建一个组件。

When I reference this in any of the the lifecycle hooks ( created , mounted , updated , etc.) it evaluates to undefined

 mounted: () => {
  console.log(this); // logs "undefined"
},


我的计算属性中也发生了同样的事情:

 computed: {
  foo: () => {
    return this.bar + 1;
  }
}

我收到以下错误:

未捕获的类型错误:无法读取未定义的属性“bar”

为什么在这些情况下 this 评估为 undefined

原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 665
2 个回答

这两个示例都使用 箭头函数 () => { } ,它将 this 绑定到与 Vue 实例不同的上下文。

根据 文档

不要在实例属性或回调上使用箭头函数(例如 vm.$watch('a', newVal => this.myMethod()) )。由于箭头函数绑定到父上下文, this 不会是您期望的 Vue 实例,并且 this.myMethod 将是未定义的。

为了正确引用 this 作为 Vue 实例,请使用常规函数:

 mounted: function () {
  console.log(this);
}

或者,您也可以对函数使用 ECMAScript 5 简写

 mounted() {
  console.log(this);
}

原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议

您正在使用 箭头函数

Vue 文档 明确声明不要在属性或回调上使用箭头函数。

与常规函数不同,箭头函数不绑定 this 。相反, this 是在词法上绑定的(即 this 保留其原始上下文的含义)。

 var instance = new  Vue({
    el:'#instance',
  data:{
    valueOfThis:null
  },
  created: ()=>{
    console.log(this)
  }
});

这会在控制台中记录以下对象:

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

而……如果我们使用常规函数(我们应该在 Vue 实例上)

 var instance = new  Vue({
    el:'#instance',
  data:{
    valueOfThis:null
  },
  created: function(){
    console.log(this)
  }
});

在控制台中记录以下对象:

hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}

原文由 Ashutosh Narang 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏