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...') }
Since the Nuxt2 router is based on Vue-Router3, when you use both
push({name: ''})
and path('path string')代码>Layout/default.vue
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