调用errorMsg时,内部的this指向undefind,如何用apply让errorMsg的this指向vue
methods: {
checkGoodForm() {
function errorMsg(msg) {
this.$message.error(msg)
}
this.goodForm.tilte === '' && errorMsg('标题不能为空')
this.goodForm.tilte.length < 20 && errorMsg('标题最少十个汉字')
}
}
tilte 单词拼错了,应该是title
首先按照你的要求errorMsg.call(this, "标题不能为空")
可以满足,但是语句逻辑不对,为空的时候会将两个错误提示展示出来,建议改成下方两种写法之一
checkGoodForm() {
function errorMsg(msg) {
this.$message.error(msg);
}
if (!this.goodForm.title) return errorMsg.call(this, "标题不能为空");
if (this.goodForm.title.length < 20) errorMsg.call(this, "标题最少十个汉字");
},
更常规的是箭头函数这种
checkGoodForm() {
const errorMsg = msg => {
this.$message.error(msg);
}
if (!this.goodForm.title) return errorMsg("标题不能为空");
if (this.goodForm.title.length < 20) errorMsg("标题最少十个汉字");
},
使用箭头函数
每个function函数(非箭头函数)在每次调用时都会在函数内生成一个自己的this。
当两个函数嵌套定义时,内层函数中的this与外层函数中的this是完全独立的。
要内层函数中的调用外层函数中的this
最简单的方法是,可以在外层函数中用一个变量保存外层函数的this
var __this = this;
内层函数中用这个变量代替this
function errorMsg(msg) {
__this.$message.error(msg)
}
methods: {
checkGoodForm() {
var __this = this;
function errorMsg(msg) {
__this.$message.error(msg)
}
this.goodForm.tilte === '' && errorMsg('标题不能为空')
this.goodForm.tilte.length < 20 && errorMsg('标题最少十个汉字')
}
}