Home > front end >  Nuxt - watch route change
Nuxt - watch route change

Time:04-01

I know this was asked a couple of times, but I do not understand something about watching for a route change in nuxt.

It doesn't work for me.

My code is:

watch: {
    $route(to, from) {
      console.log('route change to', to)
      console.log('route change from', from)
    },
  },

Minimal reproducable example:

https://codesandbox.io/s/dreamy-feather-90gbjm

Expected behavior

show console logs on route change.

result

nothing happens

CodePudding user response:

You could solve this by adding the watcher on the layout that the index and about pages are rendered.

| pages
  | index.vue
  | about.vue
| layouts
  | base.vue

In layouts/base.vue

<template>
  <Nuxt />
</template>

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

In index.vue and about.vue

<template>
  ... Many things here
</template>

<script>
export default {
  layout: 'base',
  ...
}
</script>
  • Related