Home  >  Q&A  >  body text

Observe global route changes and perform certain operations in Nuxt2

I'm using Nuxt JS v2 and need to run a function during every page change and page load, I know I can add a route observer to the layout, but that means it has to be added to every layout, I have many, for example:

<script>
export default {
  watch: {
    $route(to, from) {
      console.log('route change to', to)
      console.log('route change from', from)
    }
  }
}
</script>

I have a plugin called cookie-tracking.js and hope that if I add a console.log to it, it will be called on every page change, But no, what could I add to make this behavior happen:

export default ({ app, route }, inject) => {
  console.log('run on each page change...')
}

P粉649990163P粉649990163303 days ago485

reply all(1)I'll reply

  • P粉145543872

    P粉1455438722023-12-22 15:47:12

    Since the Nuxt2 router is based on Vue-Router3, when you use both push({name: ''}) and <代码>path('path string')

    Layout/default.vue

    // https://v3.router.vuejs.org/api/#route-object-properties
    computed: {
        fullPath() {
            return this.$route.fullPath;
        },
        path() {
            return this.$route.path;
        }
    },
    watch: {
        // /a/b?c=d => /a/b?c=e will trigger this
        fullPath(newFullPath) {
            // do something
        },
        // /a/b => /a/c will trigger this, the above won't
        path(newPath) {
            // do something
        }
    }
    
    // or just watch with quote
    
    watch: {
        '$route.fullPath'(newFullPath) {
            // do something
        },
    }

    Considering your use case (cookie-tracking.js), you may only fire the event once when changing the path, so you can put it in layout/default.vue< /strong> Instead of each Nuxt-Page-Component, if you have multiple layouts, you may consider refactoring the code to mixin

    reply
    0
  • Cancelreply