场景说明,如图,首页有个列表,点击加号后,会弹出一个表单,希望实现在显示表单后,点击回退,不是改变路由或者返回前一页,而是关闭弹出的表单。
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使用
} };
index.vue接收到关闭事件后处理
store.commit(‘allowBack‘); // 状态改变,改为可以后退 window.onpopstate = event => {}; // 清除onpopstate事件,同上面一样,不要使用addEventListener
this.formVisible = false;
原文:https://www.cnblogs.com/saving/p/10822088.html