VueRouter-组件守卫
组件导航守卫,就是组件中写守卫。也就是进入到这个组件之前会调用的方法。组件导航守卫大体分为:`beforeRouteEnter`、`beforeRouteUpdate`、`beforeRouteLeave`三个。
beforeRouteEnter:在进入组件之前调用的。在这里不能使用`this`,因为,该组件还没有实例化。
beforeRouteUpdate:防止组件重用。
beforeRouteLeave:即将离开这个组件的时候调用的。
整体代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <title>VueRouter-组件守卫</title> </head> <body> <div id="app"> <router-link to="/account">我的账户</router-link> <router-link to="/order">订单</router-link> <router-view></router-view> </div> <script> var account = Vue.extend({ data: function () { return { username: "Xsan" } }, template: "<h1>账户</h1>", beforeRouteEnter: function (to, from, next) { console.log("to:", to) console.log("from:", from) console.log(this.username) next(vm => { // 此时可以通过vm访问属性 console.log("username:", vm.username) }) }, beforeRouteUpdate: function (to, from, next) { console.log("to:", to) console.log("from:", from) console.log(this.username) }, beforeRouteLeave: function (to, from, next) { const anwser = window.confirm("您确认离开这个页面吗?") if (anwser) { next() } } }) var order = Vue.extend({ template: "<h1>订单</h1>" }) let router = new VueRouter({ routes: [{ path: "/account", component: account, name: "account" }, { path: "/order", component: order, name: "order" }] }) new Vue({ el: "#app", router, }) </script> </body> </html>