Javascript 如果用户关闭选项卡,则发布请求,Vuejs
若用户试图关闭选项卡或更改路线,我会尝试发出post请求。但我得到一个变量的空值Javascript 如果用户关闭选项卡,则发布请求,Vuejs,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,若用户试图关闭选项卡或更改路线,我会尝试发出post请求。但我得到一个变量的空值 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 con
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\u id
的原因是您没有使用箭头函数。在您目前的情况下,这个
关键字指向事件,而不是vue实例
如果将此箭头功能用于侦听器事件,则可以访问问题\u 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;
});
},
什么变量是空的?何时调用detectTabClose?在已创建的已调用中。此.question_id为空。这篇文章是在我试图关闭选项卡时发表的,但该变量为空。似乎您是在之前调用此函数的。问题id
已初始化。尝试在用数据初始化后调用它,或者将json创建插入到Listener中它在页面呈现和问题id设置后调用。问题是,在这个方法中,我无法从VueJs访问var/方法