美文网首页
Vue页面禁止浏览器返回或者点击浏览器返回时执行对话框实现

Vue页面禁止浏览器返回或者点击浏览器返回时执行对话框实现

作者: 莫伊剑客 | 来源:发表于2021-01-07 15:06 被阅读0次

    禁止返回

    export default {
    mounted () {
    // 返回监听
    if (window.history && window.history.pushState) {
    // console.log(window.history)
    if(window.history.length>1){
    const state = {
    key: Math.random() * new Date().getTime()
    };
    window.history.pushState(state, null, document.URL);
    }
    window.addEventListener('popstate', this.backFn, false);
    }
    },
    methods: {
    backFn (e) {
    // console.log(e)
    // 返回执行逻辑 此处还可以添加对话框
    const state = {
    key: Math.random() * new Date().getTime()
    };
    window.history.pushState(state, null, document.URL);
    }
    },
    destroyed () {
    // 销毁监听
    window.removeEventListener('popstate', this.backFn, false);
    }
    };

    只有state一直在变化,点击返回的时候才能触发popstate

    相关文章

      网友评论

          本文标题:Vue页面禁止浏览器返回或者点击浏览器返回时执行对话框实现

          本文链接:https://www.haomeiwen.com/subject/bnyzoktx.html