zoukankan      html  css  js  c++  java
  • vue+vuex+router实现阻止浏览器回退

    场景说明,如图,首页有个列表,点击加号后,会弹出一个表单,希望实现在显示表单后,点击回退,不是改变路由或者返回前一页,而是关闭弹出的表单。

    index.vue(页面) 和 form.vue(组件)

    用vuex的store作为 页面和组件的通信

    import Vuex from 'Vuex'
    
    const store = new Vuex.Store({
        state:{
            canBack: true
        },
        mutations:{
            allowBack: state => state.canBack = true,
            notAllowBack: state => {
                state.canBack = false
                history.pushState(null, null, location.href)
            }
        }
    })
    
    export default store;
    

      

    index.vue 点击加号事件中要,设置不能回退

      store.commit("notAllowBack");
    

     

    然后让组件显示

    form组件在mounted时添加window监听(重点

    // 必须用window.onpopstate 而不是 window.addEventListener,不然面不好清除   
    window.onpopstate = event => { if (!store.state.canBack) { history.go(1); // 重点,这是阻止回退事件,要配合 store里的 history.pushState使用
          this.$emit("quite"); // 提交退出事件,讓外部處理
          }
        };
    

      

    index.vue接收到关闭事件后处理

    store.commit('allowBack'); // 状态改变,改为可以后退
    window.onpopstate =  event => {}; // 清除onpopstate事件,同上面一样,不要使用addEventListener
    this.formVisible = false;

      

  • 相关阅读:
    VUE DEVTOOLS 安装方法(npm cnpm 安装失败找不到安装工具问题解决方法)
    idea 注释模版
    阿里巴巴编码规范
    JRebel 实现热部署
    SPRING 扩展组件
    oracle 闪回
    ORACLE 日常
    springboot log4j
    支付宝异步回调验证签名的那些走过的坑
    ASP.NET MVC5(一)—— URL路由
  • 原文地址:https://www.cnblogs.com/saving/p/10822088.html
Copyright © 2011-2022 走看看