VueJS & Laravel,在用户离开屏幕时发出后请求

VueJS & Laravel, do a post request when user leaves screen

本文关键字:屏幕 请求 离开 用户 amp Laravel VueJS      更新时间:2023-09-26

请寻求一些帮助。

我需要检查输入是否已填写,然后如果用户将屏幕留给选项卡或后退按钮等,则会发生发布请求。

 sendSMS: function(e) {
        if(this.to) {
            this.$http.post('/demo/send', message)
        }
 }

当输入不为空时,我需要说些什么,如果用户离开站点区域屏幕,即朝向选项卡或后退按钮上升,然后执行发布请求。因此,不会按下按钮来提交此内容,而是检查输入是否已填写以及用户是否离开屏幕。

在我使用的上述方法中使用 VueJS 如何做到这一点?

在页面关闭时运行 js 函数:在窗口关闭或页面刷新时运行 JavaScript 代码?

你需要在 Vue 的 ready 函数中添加事件侦听器:

....
data:function(){
    return {sentRequest:false}
},
ready:function(){
    window.onbeforeunload = this.leaving;
    window.onblur = this.leaving;
    window.onmouseout = this.leaving;
},
methods:{
    leaving:function(){
        if(!this.sentRequest){
             //do stuff
             this.sentRequest = true;
        }
        return null;
    }
}
....