Dollique
Dollique

Reputation: 1012

Nuxt2 - watch route change

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

Upvotes: 7

Views: 21551

Answers (2)

KitKit
KitKit

Reputation: 9523

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

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

onBeforeRouteUpdate((newRoute) => {
    console.log(newRoute)
})
</script>

Upvotes: 2

Guille
Guille

Reputation: 714

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>

Upvotes: 9

Related Questions