为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

神不在的星期二 2022-06-09 19:12:51
如果用户尝试关闭选项卡或更改路线,我会尝试发出发布请求。但是我得到一个变量的空值。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;  });},
查看完整描述

1 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

您无法访问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;

  });

},


查看完整回答
反对 回复 2022-06-09
  • 1 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号