通过使用散列路由的后退按钮关闭模态



我在vuejs中有一个模态,我通过传递道具isActive来打开/关闭它,并且我想在用户单击后退按钮时关闭该模态。

当模态打开时,我将散列#modal添加到url,当模态关闭时,我删除散列。

我试图在用户单击后退按钮时关闭模态,但目前没有,它只是删除了哈希。

如果我单击close()方法,模态将关闭,因此看起来eventListener()工作不正常。

当用户单击后退按钮时,我如何关闭模态?

modal.js

import { mapActions, mapGetters } from 'vuex';

export default {
props: {
isActive: {
type: Boolean,
default: false,
},
},
computed: {
hashChange() {
console.log(this.isActive)
if(this.isActive) {
window.location.assign('#modal')
} else {
history.replaceState({}, document.title, window.location.href.split('#')[0]);
}
},
},
methods: {
close() {
this.$emit('close');
},
},
mounted() {
window.addEventListener('hashchange', this.close());
},
destroyed() {
window.addEventListener('hashchange', this.close());
},
};

HashChange是基于isActive值的,isActive值是基于HashChange的,所以它是循环的,当然这种方式不起作用。相反,你可以直接听下面的后退按钮,然后完全删除HashChange。在这种情况下,它是无用的:

methods: {
close() {
this.$emit('close');
},
},
mounted () {
document.addEventListener("backbutton", this.close, false);
},
beforeDestroy () {
document.removeEventListener("backbutton", this.close);
}

在路由器中添加:

// This listener will execute before router.beforeEach only if registered
// before vue-router is registered with Vue.use(VueRouter)
window.popStateDetected = false
window.addEventListener('popstate', () => {
window.popStateDetected = true
})

router.beforeEach((to, from, next) => {
const IsItABackButton = window.popStateDetected
window.popStateDetected = false
if (IsItABackButton && from.name === //The name of the route you are using) {
next(false) 
}
next()
})

最新更新