1👍
✅
The reason you cannot access to this.question_id
inside the window.addEventListener
is that you’re not using an arrow function. In your case right now, this
keyword points to the event instead of vue instance.
If you use this arrow function for listener event, you can access the 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;
});
},
Source:stackexchange.com