Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果用户关闭选项卡,则发布请求,Vuejs_Javascript_Vue.js_Vuejs2 - Fatal编程技术网

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

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

若用户试图关闭选项卡或更改路线,我会尝试发出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 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/方法