TypeScripy + Vue Property Decorator + Vue Router,組件內的導航守衛無效


組件內守衛

  1. beforeRouteEnter
  2. beforeRouteUpdate (2.2 新增)
  3. beforeRouteLeave
  4. 官網鏈接

注意事項

  • 直接在class中定義這3個鈎子函數無效,函數不會觸發

  • 需要先registerHooks,如下

  • 方式一(直接在組件中register)
<template>
    <h1>直接在class中定義這3個鈎子函數無效不會觸發,需要先`registerHooks`</h1>
</template>

<script lang='ts'>
    import { Component, Vue } from "vue-property-decorator";

    @Component({
        beforeRouteEnter(to, from, next) {
            // 在渲染該組件的對應路由被 confirm 前調用
            // 不!能!獲取組件實例 `this`
            // 因為當守衛執行前,組件實例還沒被創建
            console.log("路由進來了");
            next();
        },
        beforeRouteUpdate(to, from, next) {
            // 在當前路由改變,但是該組件被復用時調用
            // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
            // 由於會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。
            // 可以訪問組件實例 `this`
            console.log("路由更新了");
            next();
        },

        beforeRouteLeave(to, from, next) {
            // 導航離開該組件的對應路由時調用
            // 可以訪問組件實例 `this`
            console.log("路由離開了");
            next();
        }
    })
    export default class Chat extends Vue {
        
    }
</script>
  • 方式二(在全局register,注冊后就可以在class中正常使用)
import { Component } from "vue-property-decorator";

Component.registerHooks(["beforeRouteEnter", "beforeRouteLeave", "beforeRouteUpdate"]);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM