标签:char dex link tps pre 过程 let auth login
router.beforeEach(function (to, from, next) { // to:将要跳转到哪个页面 // from:从哪个页面来的 // next: // next():按照正常流程跳转 // next("path"):跳转到指定的path路径 // next(false)或者没有调用next():则不做任何跳转 const authRoutes = ["account", "order"] // 判断要访问的页面是否为必须登录的页面 if (authRoutes.indexOf(to.name) >= 0) { if (!logined) { // 没有登录,跳转到登录页面 next("/login") } else { next() } } else { if (to.name == "login") { if (logined) { next("/") } else { next() } } else { // 当其访问的不是必须登录的页面或者不是登录页面时,直接正常跳转 next() } } })
router.afterEach(function (to, from) { console.log("to:", to) console.log("from:", from) })
{ path: "/login", component: login, name: "login", beforeEnter: function (to, from, next) { if (logined) { next("/") } else { next() } } }
<!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="/">首页</router-link> <router-link to="/account">我的账户</router-link> <router-link to="/order">订单</router-link> <router-link to="/login">登录</router-link> <router-view></router-view> </div> <script> const logined = false var index = Vue.extend({ template: "<h1>首页</h1>" }) var account = Vue.extend({ template: "<h1>账户</h1>" }) var order = Vue.extend({ template: "<h1>订单</h1>" }) var login = Vue.extend({ template: "<h1>登录</h1>" }) let router = new VueRouter({ routes: [{ path: "/", component: index, name: "index" }, { path: "/account", component: account, name: "account" }, { path: "/order", component: order, name: "order" }, { path: "/login", component: login, name: "login", beforeEnter: function (to, from, next) { if (logined) { next("/") } else { next() } } }] }) router.beforeEach(function (to, from, next) { // to:将要跳转到哪个页面 // from:从哪个页面来的 // next: // next():按照正常流程跳转 // next("path"):跳转到指定的path路径 // next(false)或者没有调用next():则不做任何跳转 const authRoutes = ["account", "order"] // 判断要访问的页面是否为必须登录的页面 if (authRoutes.indexOf(to.name) >= 0) { if (!logined) { // 没有登录,跳转到登录页面 next("/login") } else { next() } } else { if (to.name == "login") { if (logined) { next("/") } else { next() } } else { // 当其访问的不是必须登录的页面或者不是登录页面时,直接正常跳转 next() } } }) router.afterEach(function (to, from) { console.log("to:", to) console.log("from:", from) }) new Vue({ el: "#app", router, }) </script> </body> </html>
标签:char dex link tps pre 过程 let auth login
原文地址:https://www.cnblogs.com/xshan/p/12364443.html