7

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

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

Kalnode
  • 9,386
  • 3
  • 34
  • 62
Dollique
  • 952
  • 2
  • 10
  • 29
  • 1
    Probably because you watch it only in a specific page, hence when you're coming or leaving it, it's not watching it the first time. (maybe `immediate: true` could help here) Still, it's probably better to have this kind of watcher in a middleware or in a wrapping layout. – kissu Mar 30 '22 at 22:35

2 Answers2

9

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>
kissu
  • 40,416
  • 14
  • 65
  • 133
Guille
  • 614
  • 3
  • 10
  • 1
    Or use the `/layouts/default.vue`, that way you don't even need to specify it. – kissu Mar 31 '22 at 00:10
  • Nice, this worked. I was trying to setup the watcher in a component. It makes sense if you think about it, because routes only work for the whole page and not a component itself. – Dollique Mar 31 '22 at 20:24
2

With Nuxt 3, you can use onBeforeRouteUpdate from vue-router:

<script setup>
import { onBeforeRouteUpdate } from "vue-router"

onBeforeRouteUpdate((newRoute) => {
    console.log(newRoute)
})
</script>
KitKit
  • 8,549
  • 12
  • 56
  • 82