首页  >  问答  >  正文

观察全局路由变化并在 Nuxt2 中执行某些操作

我正在使用 Nuxt JS v2,需要在每次页面更改和页面加载期间运行一个函数,我知道我可以在布局中添加路由观察器,但这意味着必须将其添加到每个布局中,我有很多,例如:

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

我有一个名为 cookie-tracking.js 的插件,希望如果我添加一个 console.log 到它,它会在每个页面更改时被调用,但是不,什么可以我添加了这种行为的发生:

export default ({ app, route }, inject) => {
  console.log('run on each page change...')
}

P粉649990163P粉649990163303 天前477

全部回复(1)我来回复

  • P粉145543872

    P粉1455438722023-12-22 15:47:12

    由于 Nuxt2 路由器基于 Vue-Router3,因此当您同时使用 push({name: ''}) 和 <代码>路径('路径字符串')

    布局/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
        },
    }

    考虑到您的用例(cookie-tracking.js),您可能在更改路径时仅触发一次事件,因此您可以将其放入layout/default.vue< /strong> 而不是每个 Nuxt-Page-Component,如果您有多种布局,您可以考虑将代码重构为 mixin

    回复
    0
  • 取消回复