“TypeError:无法读取未定义的属性‘$emit’” - VueJS
2019-04-09
21493
1个回答
ES5 函数有自己的
this
,因此请将
this.$parent.mockAccount.forEach(function (element) {
if (enteredUsername === element.username && enteredPassword === element.password) {
this.$emit("authenticated", true)
this.$router.replace({name: "secure"})
}
})
更改为 ES6 箭头函数(其具有与定义它们的上下文相同的
this
)
this.$parent.mockAccount.forEach((element) => {
if (enteredUsername === element.username && enteredPassword === element.password) {
this.$emit("authenticated", true)
this.$router.replace({name: "secure"})
}
})
或使用
Function.prototype.bind()
(ES5) 进行显式绑定:
this.$parent.mockAccount.forEach(function (element) {
if (enteredUsername === element.username && enteredPassword === element.password) {
this.$emit("authenticated", true)
this.$router.replace({name: "secure"})
}
}.bind(this))
或使用闭包:
const self = this;
this.$parent.mockAccount.forEach(function (element) {
if (enteredUsername === element.username && enteredPassword === element.password) {
self.$emit("authenticated", true)
self.$router.replace({name: "secure"})
}
})
connexo
2019-04-09