router.beforeEach((to, from, next) => {
// ...
})
to: Route
: 即将要进入的目标路由对象 ![bd88d0b660481a15e489622bb2baab9d259.jpg](https://oscimg.oschina.net/oscnet/bd88d0b660481a15e489622bb2baab9d259.jpg)
from: Route
: 当前导航正要离开的路由![a286cb806940ed3d8e746edb14933165418.jpg](https://oscimg.oschina.net/oscnet/a286cb806940ed3d8e746edb14933165418.jpg)
next: Function
: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next
方法的调用参数。
next()
: 直接跳转到to.path路径。进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。next(false)
: 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from
路由对应的地址。next('/')
或者 next({ path: '/' })
: 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
- 案例
const whiteList = ['/author']
router.beforeEach((to, from, next) => {
//判断是不是登录
let token = getToken();
if (common_fuc.isDefine(token)) {
if (to.path === '/author') {
next({ path: '/' });
} else {
next();
}
} else {
//如果没有登录 判断to.path是否是/author 是就直接next()去首页,否则登录
if (whiteList.indexOf(to.path) !== -1) {
//微信登录返回页面继续 或跳转到登录页面
next()
} else if(isWeiXin()==true&&config_site.is_debug==false){
//如果是微信登录 并且不是调试模式
setBeforeLoginUrl(to.fullPath);
getWxAuth();
}
}
next();
})