路由跳转前作一些验证,好比登陆验证,是网站中的广泛需求。html
对此,vue-route 提供的 beforeRouteUpdate 能够方便地实现导航守卫(navigation-guards)。vue
导航守卫(navigation-guards)这个名字,听起来怪怪的,但既然官方文档是这样翻译的,就姑且这么叫吧。vue-router
贴上文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.htmlapi
你可使用 router.beforeEach
注册一个全局前置守卫:浏览器
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
当一个导航触发时,全局前置守卫按照建立顺序调用。守卫是异步解析执行,此时导航在全部守卫 resolve 完以前一直处于 等待中。异步
每一个守卫方法接收三个参数:网站
to: Route
: 即将要进入的目标 路由对象spa
from: Route
: 当前导航正要离开的路由翻译
next: Function
: 必定要调用该方法来 resolve 这个钩子。执行效果依赖 next
方法的调用参数。code
next()
: 进行管道中的下一个钩子。若是所有钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false)
: 中断当前的导航。若是浏览器的 URL 改变了(多是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from
路由对应的地址。
next('/')
或者 next({ path: '/' })
: 跳转到一个不一样的地址。当前的导航被中断,而后进行一个新的导航。
next(error)
: (2.4.0+) 若是传入 next
的参数是一个 Error
实例,则导航会被终止且该错误会被传递给 router.onError()
注册过的回调。
确保要调用 next
方法,不然钩子就不会被 resolved。
下面写一个例子:
import Vue from 'vue'; import Router from 'vue-router'; import LoginPage from '@/pages/login'; import HomePage from '@/pages/home'; import GoodsListPage from '@/pages/good-list'; import GoodsDetailPage from '@/pages/good-detail'; import CartPage from '@/pages/cart'; import ProfilePage from '@/pages/profile'; Vue.use(Router) const router = new Router({ routes: [ { path: '/', // 默认进入路由 redirect: '/home' //重定向 }, { path: '/login', name: 'login', component: LoginPage }, { path: '/home', name: 'home', component: HomePage }, { path: '/good-list', name: 'good-list', component: GoodsListPage }, { path: '/good-detail', name: 'good-detail', component: GoodsDetailPage }, { path: '/cart', name: 'cart', component: CartPage }, { path: '/profile', name: 'profile', component: ProfilePage }, { path: '**', // 错误路由 redirect: '/home' //重定向 }, ] }); // 全局路由守卫 router.beforeEach((to, from, next) => { console.log('navigation-guards'); // to: Route: 即将要进入的目标 路由对象 // from: Route: 当前导航正要离开的路由 // next: Function: 必定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。 const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile']; let isLogin = global.isLogin; // 是否登陆 // 未登陆状态;当路由到nextRoute指定页时,跳转至login if (nextRoute.indexOf(to.name) >= 0) { if (!isLogin) { console.log('what fuck'); router.push({ name: 'login' }) } } // 已登陆状态;当路由到login时,跳转至home if (to.name === 'login') { if (isLogin) { router.push({ name: 'home' }); } } next(); }); export default router;