观察全局路由变化并在 Nuxt2 中执行某些操作
P粉649990163
P粉649990163 2023-12-21 18:00:30
0
1
473

我正在使用 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粉649990163
P粉649990163

全部回复(1)
P粉145543872

由于 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 而不是每个 Nuxt-Page-Component,如果您有多种布局,您可以考虑将代码重构为 mixin

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!