Nuxt2 - 观察路线变化

Tob*_*oby 7 vue.js vue-router nuxt.js

我知道这个问题被问过几次,但我不明白在 Nuxt2 中观察路线变化的一些事情。

这对我不起作用。

我的代码是:

watch: {
    $route(to, from) {
      console.log('route change to', to)
      console.log('route change from', from)
    },
  },
Run Code Online (Sandbox Code Playgroud)

最小可重现示例:

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

预期行为

显示有关路线更改的控制台日志。

结果

什么都没发生

Gui*_*lle 9

layout您可以通过在呈现索引和关于页面时添加观察器来解决此问题。

| pages
  | index.vue
  | about.vue
| layouts
  | base.vue
Run Code Online (Sandbox Code Playgroud)

在layouts/base.vue

| pages
  | index.vue
  | about.vue
| layouts
  | base.vue
Run Code Online (Sandbox Code Playgroud)

在index.vue和about.vue

<template>
  <Nuxt />
</template>

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