Vue中this为undefined的问题及无_this的解决办法
问题原因
报错的根源是你在res.field_names.forEach()里用了普通function作为回调——普通函数会创建自己的作用域,导致函数内部的this不再指向Vue组件实例,所以触发TypeError: this is undefined。
解决办法(不用
let _this = this) 方案1:用箭头函数替代普通函数
箭头函数不会绑定自身的this,会继承外层上下文的this(也就是Vue实例),直接替换forEach的回调函数即可:
修改后的关键代码片段:
if( isRefreshed ) { res.field_names.forEach((item, index) => { // 换成箭头函数 this.mappingData.newProjectFieldOptions.push({ value: item, text: "Do Not Import", custom: null, }); }); // ... 其他代码不变 } else { res.field_names.forEach((item, index) => { // 换成箭头函数 this.mappingData.projectFieldOptions.push({ value: item, text: "Do Not Import", custom: null, }); }); }
方案2:利用forEach的第二个参数绑定this
Array.prototype.forEach()的第二个参数可以指定回调函数内部的this指向,直接把Vue实例的this传进去就行:
修改后的关键代码片段:
if( isRefreshed ) { res.field_names.forEach(function (item, index) { this.mappingData.newProjectFieldOptions.push({ value: item, text: "Do Not Import", custom: null, }); }, this); // 第二个参数传入this,绑定回调的this指向 // ... 其他代码不变 } else { res.field_names.forEach(function (item, index) { this.mappingData.projectFieldOptions.push({ value: item, text: "Do Not Import", custom: null, }); }, this); // 第二个参数传入this }
两种方案都能解决问题,选你习惯的写法即可。
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

