未按预期触发Vuejs 'beforeunload'事件

ldioqlga  于 2022-11-25  发布在  Vue.js
关注(0)|答案(5)|浏览(274)

我已经在vue路由器的路由所使用的组件的创建钩子上注册了“beforeunload”事件。

我希望调用此事件处理程序,以便在浏览器选项卡关闭,浏览器选项卡刷新或浏览器关闭时删除用户

在组件A上

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}

在组件B上微笑

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}

还有我的router.js

{
  path: '/staff/call/:session_key',
  name: 'Staff Call',
  component: ComponentA,
  meta: {auth: true}
},
{
  path: '/consumer/call/:session_key',
  name: 'Consumer Call',
  component: ComponentB
},

这里'beforeunload'事件处理程序是随机触发,也就是说,它有时被触发,有时不被触发,我计算它被触发和不被触发时找到任何模式
我错过了什么?

vd2z7a6w

vd2z7a6w1#

编辑

我猜最有可能的罪魁祸首就是PatrickSteele所说的。
注意:为了防止出现不需要的弹出窗口,某些浏览器不显示beforeunload事件处理程序中创建的提示,除非页面已经被交互;有些根本不显示它们。要获得特定浏览器的列表,请参阅Browser_compatibility部分。
我认为您看到的行为可能不一致,因为您有时无法与页面进行交互。
这可能是语法错误。created应该是方法

created () {    
        window.addEventListener('beforeunload', this.removeUser)  
    },

    methods: {
      removeUser () {
        //remove user here
      }
    }

小提琴:https://jsfiddle.net/e6m6t4kd/3/

yhived7q

yhived7q2#

这对我很有用。在重新加载或关闭vue.js之前执行一些操作

created() {
    window.onbeforeunload = function(){
           return "handle your events or msgs here";
    }
}
3gtaxfhh

3gtaxfhh3#

我不得不在上面的例子上做一些修饰,我相信这是最健壮的解决方案:

let app1 = new Vue({
    delimiters: ['[[', ']]'],       
    el: '#app',
    data: {
        dirty_form: true,
    },

    created () {
        console.log('created')
        window.addEventListener('beforeunload', this.confirm_leaving)
    },

    methods: {
        confirm_leaving (evt) {
            if (this.dirty_form) {
                const unsaved_changes_warning = "You have unsaved changes. Are you sure you wish to leave?";
                evt.returnValue = unsaved_changes_warning; 
                return unsaved_changes_warning;
            };
        };
    },
});
pxyaymoc

pxyaymoc4#

如果您希望在按F5或Ctrl + R时检测Vue中的页面刷新/更改,则可能需要使用Navigation Timing API
PerformanceNavigation.type将告诉您如何访问该页。

created() {
    // does the browser support the Navigation Timing API?
    if (window.performance) {
        console.info("window.performance is supported");
    }
    // do something based on the navigation type...
    if(performance.navigation.type === 1) {
        console.info("TYPE_RELOAD");
        this.removeUser();
    }
}
luaexgnf

luaexgnf5#

不知道为什么上面没有一个对我在vue 3 composition api中完全有效。阿卜杜拉的回答部分有效,但他遗漏了如何删除侦听器。

setup() {

  const doSomething = (e) => {
    // do stuff here
    return true
  }

  onBeforeMount(() => {
    window.onbeforeunload = handleLeaveWithoutSaving
  })

  onUnmounted(() => {
    window.onbeforeunload = null
  })

}

相关问题