目录
1.示例代码
/** 删除按钮操作 */
handleDelete(row) {
debugger
const ids = row.id || this.ids;
this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + ids + '"的数据项?').then(function () {
debugger
console.log(this);
return delStorageInMaster(this.ids);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
});
},
2.说明
点击confirm的确认按钮之后,执行function方法中的内容,如果在方法内容要使用data中定义的一个变量,使用this.ids进行引用时,发现此时的this是undefined,无法直接进行引用,原因是因为
回调函数的内部的this并非指向当前的vue实例。
3.解决方案
(1)在方法执行之前存一下this,例
/** 删除按钮操作 */
handleDelete(row) {
let _that = this;
this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + _that.ids + '"的数据项?').then(function () {
return delStorageInMaster(_that.ids);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
});
},
(2)使用箭头函数,then后面不使用function,使用箭头函数
/** 删除按钮操作 */
handleDelete(row) {
this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + this.ids + '"的数据项?').then(() => {
return delStorageInMaster(this.ids);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
});
},
(3)使用的变量存放在新的变量中,使用this.ids时,将其存放在ids变量中,后续处理不再使用this进行使用,而直接使用ids
/** 删除按钮操作 */
handleDelete(row) {
const ids = row.id || this.ids;
this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + ids + '"的数据项?').then(function () {
return delStorageInMaster(ids);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
});
},
4总结
箭头函数出现在es6,箭头函数里面没有this对象,此时的this对象指的是是外层的 this 对象,所以入如果在函数中要引用外面的this对象,推荐使用箭头函数。