如果用户尝试关闭选项卡或更改路线,我会尝试发出发布请求。但是我得到一个变量的空值。
detectTabClose() {
let newValues = {
question: this.question_id,
user_id: this.$userId //this is global, from root and is ok
};
window.addEventListener("beforeunload", function(e) {
var confirmationMessage = "o/";
(e || window.event).returnValue = confirmationMessage;
console.log(this.question_id); //I get undefined
axios
.post("/submit/answer", newValues)
.then(() => {
console.log("Post before tab closing");
})
.catch(() => {
console.log("Error on post");
});
return confirmationMessage;
});
},
您无法访问this.question_id
内部的原因window.addEventListener
是您没有使用箭头函数。就您现在的情况而言,this
关键字指向事件而不是 vue 实例。
如果将此箭头函数用于侦听器事件,则可以访问question_id
.
detectTabClose() {
let newValues = {
question: this.question_id,
user_id: this.$userId //this is global, from root and is ok
};
window.addEventListener("beforeunload", (e) => {
var confirmationMessage = "o/";
(e || window.event).returnValue = confirmationMessage;
console.log(this.question_id); // this will be accessible now
axios
.post("/submit/answer", newValues)
.then(() => {
console.log("Post before tab closing");
})
.catch(() => {
console.log("Error on post");
});
return confirmationMessage;
});
},
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句