如果用户关闭选项卡,则发布请求,Vuejs

如果用户尝试关闭选项卡或更改路线,我会尝试发出发布请求。但是我得到一个变量的空值。


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;

  });

},


神不在的星期二
浏览 116回答 1
1回答

暮色呼如

您无法访问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;  });},
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript