VueJS:为什么“这个”没有定义?我正在创建一个组件vue.js.当我提到this在任何一个生命周期钩 (created, mounted, updated等等)它评估为undefined:mounted: () => {
console.log(this); // logs "undefined"},同样的事情也发生在我的计算属性中:computed: {
foo: () => {
return this.bar + 1;
} }我得到以下错误:未定义类型错误:无法读取未定义的属性“bar”为什么this评估到undefined在这种情况下?
2 回答
翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
() => { }this
不要对实例属性或回调使用箭头函数(例如, vm.$watch('a', newVal => this.myMethod()))。当箭头函数绑定到父上下文时, this不会如您所期望的那样成为Vue实例, this.myMethod将是未知的。
this
mounted: function () {
console.log(this);}mounted() {
console.log(this);}
波斯汪
TA贡献1811条经验 获得超4个赞
thisthisthis
var instance = new Vue({
el:'#instance',
data:{
valueOfThis:null
},
created: ()=>{
console.log(this)
}});Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
var instance = new Vue({
el:'#instance',
data:{
valueOfThis:null
},
created: function(){
console.log(this)
}});hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}
添加回答
举报
0/150
提交
取消
