Observe global route changes and perform certain operations in Nuxt2
P粉649990163
P粉649990163 2023-12-21 18:00:30
0
1
531

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粉649990163
P粉649990163

reply all(1)
P粉145543872

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 Instead of each Nuxt-Page-Component, if you have multiple layouts, you may consider refactoring the code to mixin

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template