VueJS:为什么"这个"未定义?

时间:2017-05-12 05:05:12

标签: javascript vue.js this vuejs2

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

当我在lifecycle hooksthiscreatedmounted等中的任何一个中引用updated时,它会评估为{{1} }:

undefined

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

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

我收到以下错误:

  

未捕获的TypeError:无法读取属性' bar'未定义的

为什么computed: { foo: () => { return this.bar + 1; } } 在这些情况下评估this

3 个答案:

答案 0 :(得分:90)

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

根据documentation

  

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

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

this

或者,您也可以使用ECMAScript 5 shorthand作为函数:

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

答案 1 :(得分:3)

您正在使用arrow functions

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

与常规函数不同,箭头函数不会绑定<body> <div id="app"> <div class='parallax-wrapper'></div> <div class="normal-wrapper">Hello World</div> <div class='parallax-wrapper'></div> <div class="normal-wrapper">Hello World</div> </div> </body>。相反,this是按词法绑定的(即this保持其原始上下文的含义)。

this

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

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

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

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

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

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

答案 2 :(得分:0)

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

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