Skip to content
Advertisement

Closing a Modal/Menu with the back button in Vue/Nuxt

I want to close a fullscreen menu or modal when the user tap the hardware backbutton. I tried this:

<script>
    export default {
        data(){
            return{
                isMenuOpen: false
            }
        },
        methods:{
            openMenu(){
                this.isMenuOpen = true
                document.addEventListener('backbutton', this.closeMenu, false)
            },
            closeMenu(){
                this.isMenuOpen = false
                document.removeEventListener('backbutton', this.closeMenu)
            }
        }
    }
</script>

but that does not work. Can anyone help me here?

Advertisement

Answer

For this case, my code is similar with Cosimo’s Answer but with different approach.

the difference is i keep the modal triggered by the data property ( this.isMenuOpen )

data(){
  return {
    isMenuOpen: false
  }
}

So you can use it to bind in modal component

<modal v-model="isMenuOpen" />

and i add a watch property to watch the query

watch: {
  $route(newVal, oldVal) {
    this.isMenuOpen = newVal.query?.isMenuOpen || false
  }
}

then in your openMenu methods you can do this

openMenu(){
  this.isMenuOpen = true
  this.$router.push({
    name : "same-path",
    query : {
      isMenuOpen : true
    }
  })
}

But, in your closeMenu use the $router.replace instead of $router.push

closeMenu(){
  this.isMenuOpen = false
  this.$router.replace({
    name : "same-path"
  })
}



Why I use the $router.push for openModal only ? that because it save the history of state, so whenever it open the modal, it will tell the browser new state and than you still can use the back button to the previous state.
After pressed the back button it will remove the query param and it will trigger the watch property

And why use the $router.replace in closeModal ? because it will just replace the state, So when you press back button it will go back to the previous url page instead of open the modal

Advertisement