Nuxt Detect Page Enter and Page Leave

July 27, 2021

Usually you could use mounted() and beforeDestory() to detect nuxt page enter and leave, but it is not reliable if you use nuxt component keep-alive as the page component is cached and not created/destroyed each time.

Alternative would be

<script>
export default {
  data() {
    item: {},
  },
  async fetch() {
    const id = vm.$route.params.id

    // load data
    this.item = ...
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter', vm.$route, vm.item.name)
    })
  },
  beforeRouteUpdate(to, from, next) {
    console.log('beforeRouteUpdate', this.$route, this.item.name)
    next()
  },
  beforeRouteLeave(to, from, next) {
    console.log('beforeRouteLeave', this.$route, this.item.name)
    next()
  }
}
</script>
  • beforeRouteEnter: called first time the page is entered (e.g. /about to /page/123), with the current route info, this.item is empty as fetch is not called yet.
  • beforeRouteUpdate: called when the page changed (e.g./page/123 to /page/555), where the route info is the previous page, this.item is from previous page.
  • beforeRouteLeave: called when the page exist (e.g. /page/123 to /about), where the route info is the previous page, this.item is from previous page.
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.