如果用户关闭选项卡,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;
  });
},
塔希尔德米里塔斯

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当用户关闭浏览器选项卡时,我想将数据发布到API

用axios接连发布请求Vuejs

Vuejs和Laravel发布请求CORS

jQuery ajax发布请求在选项上被取消

如果发布请求成功,则关闭对话框

请求/发布用户名/登录无效

JavaScript-在选项卡关闭时发送AJAX调用(删除请求)

Charles请求“文本”选项卡

在laravel中发布axios(VueJS)的请求给500错误

Firebase 请求 url 在网络选项卡的请求负载中显示用户名和密码

Ajax发布仅针对某些用户请求403错误?

使用javascript在发布请求中传递用户输入变量

检查是否安装了扩展程序,如果用户删除了扩展程序,则关闭选项卡

拒绝尚未发布的文件的发布文件请求。尝试了所有选项但没有奏效

通过ajax将数据发布到新选项卡

VueJS和Laravel,在用户离开屏幕时发出发布请求

卷曲请求-在xml之后发布用户和密码时无效的xml请求

如果刷新或选项卡关闭,则 Dropzone 删除文件

每个选项卡一个请求还是所有选项卡一个请求?

检测用户是否离开选项卡,Vuejs

VueJS 动态选项卡

HTTP发布到Web API 2-收到选项请求,未处理进一步的请求

VueJS/Laravel - vue-resource 在发布请求时总是给出 419 状态

AngularJS选择选项不将值传递到http发布请求中

如果打开其他选项卡,请关闭其他选项卡(react-native-collapsible)

jQuery UI选项卡:如果只有一个选项卡,则没有关闭按钮?

打开嵌套选项卡时选项卡关闭

Django-Allauth Facebook集成-分别请求发布到用户墙上的权限

在发布请求正文中的Json对象中发送用户名和密码是否安全?