Nuxt Detect Page Enter and Page Leave

Jul 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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.