Vue Router 简单易上手,能实现大部分的需求。可是,若是在项目里须要更细致的控制路由,以实现与其同步的效果,就须要挖掘其文档里没详细说起的内容。第一章为路由元信息用途挖掘。
大部分项目,除了登陆页、重置密码页、用户协议页之外,页面都须要验证用户身份进行访问。使用 Vue Router 能够配合后端进行双重验证。前端
(登陆)验证身份方法:ios
一、给须要验证的路由对象添加 meta 字段,里面自定义一个表明验证的字段:axios
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, meta: { requiresAuth: true // 添加该字段,表示进入这个路由是须要登陆的 } } ] } ] })
二、在全局导航钩子里验证 requiresAuth 字段:segmentfault
注意事项:后端
router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { if (!auth.loggedIn()) { // 没登陆 next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() // 确保必定要调用 next() } } else { next() // 确保必定要调用 next() } })
三、拦截 http 请求,验证用户身份数组
为了防止本地保存的 token 过时,须要拦截 http 请求,为每次请求头加上 token ,而后拦截 http 响应,根据响应内容判断是否须要跳回登陆页面从新登陆。使用 axios 的方法以下:浏览器
// http request 拦截器 axios.interceptors.request.use( config => { if (auth.loggedIn()) { // 判断是否存在token,若是存在的话,则每一个http header都加上token config.headers.Authorization = `token ${auth.loggedIn()}`; } return config; }, err => { return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // Unauthorized // 返回 401 清除token信息并跳转到登陆页面 auth.clear(); router.replace({ path: 'login', query: { redirect: router.currentRoute.fullPath } }) } } return Promise.reject(error.response.data) // 返回接口返回的错误信息 });
前端查看权限,也是配合后端进行某些页面的隐藏显示功能。通常应用于综合的办公系统,由 IT 部分配帐号,不一样部门的人只能看到本身负责的内容,例如行政部不会看到财务数据页面。ui
实现方法:this
上面第5步是为了防止用户直接在浏览器输入目标地址
能够控制显示路由固定的搭配,例如某个路由地址的 title 是固定的字符串、固定的欢迎语、固定的 favicon 等。在组件里经过 this.$route.meta.xxx 访问。url
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, meta: { title: '标题', message: '欢迎您', requiresAuth: true // 添加该字段,表示进入这个路由是须要登陆的 } } ] } ] })
第二章的内容在此 https://segmentfault.com/a/11...