[Vuejs]-Close modal by using back button with hash route

0👍

HashChange is based on isActive value and isActive value is based on hashChange so it’s circular and of course this way wont work instead you can directly listen to the back button as follows and remove hashChange completely it’s useless in this scenario:

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

In the router add:

// 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()
})

Leave a comment