首頁  >  問答  >  主體

觀察全域路由變化並在 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 天前487

全部回覆(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
  • 取消回覆