【问题标题】:VueJS: why is "this" undefined?VueJS:为什么“this”未定义?
【发布时间】:2018-08-17 02:37:17
【问题描述】:

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

当我在任何 lifecycle hookscreatedmountedupdated 等)中引用 this 时,它的计算结果为 undefined

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

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

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

我收到以下错误:

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

为什么在这些情况下this 的计算结果为undefined

【问题讨论】:

标签: javascript vue.js this vuejs2


【解决方案1】:

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

根据documentation

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

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

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

或者,您也可以将ECMAScript 5 shorthand 用于函数:

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

【讨论】:

  • 谢谢!它是如此明显,同时又如此有用。感觉只是一个赞成票是不够的!
  • 你知道为什么我必须使用逆函数(从function 切换到arrow function)才能在then() 回调中使用this 吗? github.com/Inndy/vue-clipboard2#sample-2
  • @NickeManarin 作为then 的回调传递的函数有自己的this,因此要让this 引用父上下文,您可以使用箭头函数。看到这个帖子:stackoverflow.com/questions/20279484/…
  • 它确实有效,有人能注意function()()=> 之间的区别吗?
【解决方案2】:

您正在使用arrow functions

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

与常规函数不同,箭头函数不绑定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, …}

【讨论】:

    【解决方案3】:

    如果您想继续使用箭头功能,可以将组件实例 (this) 作为参数传递,例如:

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

    【讨论】:

      【解决方案4】:

      如果要使用this,则不能使用箭头功能。因为箭头函数没有绑定this

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多