导航守卫
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"> <router-view></router-view> </div> <script src="../vue.js"></script> <script src="../vue-router.js"></script> <script> /* 全局守卫 前置守卫 router.beforeEach((to, from, next) => { to 我们要跳转的路由 from 表示我们从哪个路由跳过来的 next 守卫可以通过next控制下一步的跳转 如果写next() 则表示直接跳转到to的位置 }) 售票处指登录 动物园 指需要登录才能进入的页面 公园 指不需要登录就能进入的页面 如果我们想要在路由对象上携带一些信息,那么我们可以使用meta { path: '/path', component: '组件', meta: { key: value } } 通过meta我们可以给对应的路由中添加相关信息,以此来判断此路由是否需要验证 if (to.meta.requireAuth) { // 需要验证 } matched中包含了 自己本身路由对象及父路由和祖先路由的路由对象 */ const Index = { template: ` <div> <h3>广场</h3> <router-link to="/zoo">动物园</router-link> <router-link to="/park">公园</router-link> <router-link to="/ticket">售票处</router-link> </div> ` } const Zoo = { template: ` <div>动物园 <br> <router-view></router-view> </div> ` } const Ticket = { template: ` <div>售票处 <button @click="buy">买票</button> </div> `, methods: { buy () { // 往localStorage中添加一个属性 localStorage.setItem('ticket', 1) } } } const Park = { template: ` <div>公园</div> ` } const Tiger = { template: ` <div>老虎</div> ` } const routes = [ { path: '/', component: Index }, { path: '/zoo', component: Zoo, meta: { // a: 1 requireAuth: true }, children: [ { path: 'tiger', // /zoo/tiger component: Tiger, children: [ { path: 'letterTiger' } ] } ] }, { path: '/ticket', component: Ticket }, { path: '/park', component: Park } ] const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { console.log(to) // next('/') /* if (to.path === "/") { next() } else { next('/') } */ // 获取票 const ticket = localStorage.getItem('ticket') // if (to.path === '/zoo' || to.path === '/zoo/tiger') { // if (to.meta.requireAuth) { // to.matched.some(route => route.meta.requireAuth) if (to.matched.some(route => route.meta.requireAuth)) { if (ticket) { next() } else { next('/ticket') } } else { next() } }) const app = new Vue({ el: '#app', router }) </script> </body> </html>