I'm working with Nuxt JS v2 and need to run a function on every page change & during page loads, I understand that I can add a route watcher in my layout, but this would mean having to add it to every layout, and I have many, e.g:
<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 was hoping that if I add a console.log
to it that it would be called on each page change, but no, what could I add for this behaviour to occur:
export default ({ app, route }, inject) => {
console.log('run on each page change...')
}
CodePudding user response:
Since Nuxt2 router is based on Vue-Router3, you may watch it on a computed
attribute 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
},
}
considered your use case(cookie-tracking.js), you may triggered the event only once when change the path, so you may put it in to layout/default.vue instead of every Nuxt-Page-Component, if you has mutilple layouts, you can consider restructe the code into a mixin
CodePudding user response:
This sounds like a job for route middleware! With it, you can automatically fire off whatever code you want whenever the route changes, without needing to duplicate that code across your various layouts or pages. Here's how you can set it up:
Inside your middleware
directory, create a new JS file, cookie-tracking.js
. If you don't already have a middleware
directory, create one.
Inside that file, you will export a function:
// In middleware/cookie-tracking.js
export default function (context) {
console.log('Middleware activated! Current route: ' context.route.fullPath)
}
Note that this function can take the context object as an argument, giving you access to all sorts of app-level functionality. For this example, we're just logging a message with the current route to the console.
Now, you just need to hook it up to the router. Inside nuxt.config.js
, set the router.middleware
property like so:
// In nuxt.config.js
router: {
middleware: 'cookie-tracking',
},
You may alternatively use the array syntax here, which is useful if you have multiple pieces of middleware:
router: {
middleware: ['cookie-tracking', 'some-other-middleware'],
},
Make sure that whatever values you set on this property exactly match the names of your middleware files (but without the .js
extension on the end).
And that's it! This middleware will run on every page load and page change.
For more information, see the docs: