有一些问题不限于 Vue,还适应于其他类型的 SPA 项目。本文是以Vue为例进行说明。
一、页面权限控制
页面权限控制是什么意思呢?
就是一个网站有不同的角色,以博客园后端系统为例存在管理员(admin)和普通用户(user),要求不同的角色能访问的页面是不一样的。如果一个页面,有角色越权访问,这时就得做出限制了。
一种方法是通过动态添加路由和菜单来做控制,不能访问的页面不添加到路由表里,这是其中一种办法。
另一种办法就是所有的页面都在路由表里,只是在访问的时候要判断一下角色权限。如果有权限就允许访问,没有权限就拒绝,跳转到登录或404页面。
举个例子:
1 routes: [ 2 { 3 path: '/login', 4 name: 'login', 5 meta: { 6 roles: ['admin', 'user'] 7 }, 8 component: () => import('../components/Login.vue') 9 }, 10 { 11 path: '/home', 12 name: 'home', 13 meta: { 14 roles: ['admin'] 15 }, 16 component: () => import('../views/Home.vue') 17 } 18 ]
对应Home.vue页面控制:
1 // 这里是从后台获取的用户角色 2 const role = 'user' 3 // 页面内路由守卫 router.beforeEach 4 router.beforeEach((to, from, next) => { 5 if (to.meta.roles.includes(role)) { 6 next() 7 } else { 8 next({path: '/Login'}) 9 } 10 })
二、登录验证
网站一般只要登陆过一次后,接下来该网站的其他页面都是可以直接访问的,不用再次登陆。我们可以通过 token 或 cookie 通过全局路由守卫来实现,下面用代码来展示一下如何用 token 控制登陆验证。
1 router.beforeEach((to, from, next) => { 2 // 如果有token 说明该用户已登陆 3 if (localStorage.getItem('token')) { 4 // 在已登陆的情况下访问登陆页会重定向到首页 5 if (to.path === '/login') { 6 next({path: '/'}) 7 } else { 8 next({path: to.path || '/'}) 9 } 10 } else { 11 // 没有登陆则访问任何页面都重定向到登陆页 12 if (to.path === '/login') { 13 next() 14 } else { 15 next(`/login?redirect=${to.path}`) 16 } 17 } 18 })
三、动态菜单
写后台管理系统,估计有不少人遇过这样的需求:根据后台数据动态添加路由和菜单。为什么这么做呢?因为不同的用户有不同的权限,能访问的页面是不一样的。
3.1 动态添加路由
利用 vue-router 的 addRoutes 方法可以动态添加路由 router.addRoutes(routes: Array<RouteConfig>) 动态添加更多的路由规则。其参数必须是一个符合 routes 选项要求的数组。
举个例子:
1 const router = new Router({ 2 routes: [ 3 { 4 path: '/login', 5 name: 'login', 6 component: () => import('../components/Login.vue') 7 }, 8 {path: '/', redirect: '/home'}, 9 ] 10 })
上面的代码和下面的代码效果是一样的
1 const router = new Router({ 2 routes: [ 3 {path: '/', redirect: '/home'}, 4 ] 5 }) 6 7 router.addRoutes([ 8 { 9 path: '/login', 10 name: 'login', 11 component: () => import('../components/Login.vue') 12 } 13 ])
在动态添加路由的过程中,如果有 404 页面,一定要放在最后添加,否则在登陆的时候添加完页面会重定向到 404 页面。
3.2 动态生成菜单
假设后台返回来的数据长这样:
1 // 左侧菜单栏数据 2 menuItems: [ 3 { 4 name: 'home', 5 size: 18, 6 type: 'md-home', 7 text: '主页' 8 }, 9 { 10 text: '二级菜单', 11 type: 'ios-paper', 12 children: [ 13 { 14 type: 'ios-grid', 15 name: 't1', 16 text: '表格' 17 }, 18 { 19 text: '三级菜单', 20 type: 'ios-paper', 21 children: [ 22 { 23 type: 'ios-notifications-outline', 24 name: 'msg', 25 text: '查看消息' 26 }, 27 ] 28 } 29 ] 30 } 31 ]
来看看怎么将它转化为菜单栏,这里可以使用了市场上成熟的UI组件iview、ant design等。
大概原理是:把生成菜单的过程封装成组件,然后递归调用。在生成菜单时,需要判断一下是否还有子菜单,如果有就递归调用组件。
动态路由因为上面已经说过了用 addRoutes 来实现,现在看看具体怎么做。
首先,要把项目所有的页面路由都列出来,再用后台返回来的数据动态匹配,能匹配上的就把路由加上,不能匹配上的就不加。
最后把这个新生成的路由数据用 addRoutes 添加到路由表里。
1 const asyncRoutes = { 2 'home': { 3 path: 'home', 4 name: 'home', 5 component: () => import('../views/Home.vue') 6 }, 7 't1': { 8 path: 't1', 9 name: 't1', 10 component: () => import('../views/T1.vue') 11 }, 12 'password': { 13 path: 'password', 14 name: 'password', 15 component: () => import('../views/Password.vue') 16 }, 17 'msg': { 18 path: 'msg', 19 name: 'msg', 20 component: () => import('../views/Msg.vue') 21 }, 22 'userinfo': { 23 path: 'userinfo', 24 name: 'userinfo', 25 component: () => import('../views/UserInfo.vue') 26 } 27 } 28 29 // 传入后台数据 生成路由表 30 menusToRoutes(menusData) 31 32 // 将菜单信息转成对应的路由信息 动态添加 33 function menusToRoutes(data) { 34 const result = [] 35 const children = [] 36 37 result.push({ 38 path: '/', 39 component: () => import('../components/Index.vue'), 40 children, 41 }) 42 43 data.forEach(item => { 44 generateRoutes(children, item) 45 }) 46 47 children.push({ 48 path: 'error', 49 name: 'error', 50 component: () => import('../components/Error.vue') 51 }) 52 53 // 最后添加404页面 否则会在登陆成功后跳到404页面 54 result.push( 55 {path: '*', redirect: '/error'}, 56 ) 57 58 return result 59 } 60 61 function generateRoutes(children, item) { 62 if (item.name) { 63 children.push(asyncRoutes[item.name]) 64 } else if (item.children) { 65 item.children.forEach(e => { 66 generateRoutes(children, e) 67 }) 68 } 69 }
四、前进刷新后退不刷新
4.1 情景一
在一个列表页中,第一次进入的时候,请求获取数据。点击某个列表项,跳到详情页,再从详情页后退回到列表页时,不刷新。也就是说从其他页面进到列表页,需要刷新获取数据,从详情页返回到列表页时不要刷新。
在 App.vue编写如下代码:
1 <keep-alive include="list"> 2 <router-view/> 3 </keep-alive>
假设列表页为 list.vue,详情页为 detail.vue,这两个都是子组件。我们在 keep-alive 添加列表页的名字,缓存列表页。然后在列表页的 created 函数里添加 ajax 请求,这样只有第一次进入到列表页的时候才会请求数据,当从列表页跳到详情页,再从详情页回来的时候,列表页就不会刷新。
4.2 情景二
在情景一的基础上,再加一个需求:可以在详情页中删除对应的列表项,这时返回到列表页时需要刷新重新获取数据。
4.2.1 解决方案一
我们可以在路由配置文件上对 detail.vue 增加一个 meta 属性。
1 { 2 path: '/detail', 3 name: 'detail', 4 component: () => import('../view/detail.vue'), 5 meta: {isRefresh: true} 6 }
这个 meta 属性,可以在详情页中通过 this.$route.meta.isRefresh 来读取和设置。
设置完这个属性,还要在 App.vue 文件里设置 watch 一下 $route 属性。
1 watch: { 2 $route(to, from) { 3 const fname = from.name 4 const tname = to.name 5 if (from.meta.isRefresh || (fname != 'detail' && tname == 'list')) { 6 from.meta.isRefresh = false 7 // 在这里重新请求数据 8 } 9 } 10 }
这样就不需要在列表页的 created 函数里用 ajax 来请求数据了,统一放在 App.vue 里来处理。
触发请求数据有两个条件:
- 从其他页面(除了详情页)进来列表时,需要请求数据。
- 从详情页返回到列表页时,如果详情页 meta 属性中的 isRefresh 为 true,也需要重新请求数据。
当我们在详情页中删除了对应的列表项时,就可以将详情页 meta 属性中的 isRefresh 设为 true。这时再返回到列表页,页面会重新刷新。
4.2.2 解决方案二
对于上述情景其实还有一个更简洁的方案,那就是使用 router-view 的 key 属性。
1 <keep-alive> 2 <router-view :key="$route.fullPath"/> 3 </keep-alive>
首先 keep-alive 让所有页面都缓存,当你不想缓存某个路由页面,要重新加载它时,可以在跳转时传一个随机字符串,这样它就能重新加载了。
例如从列表页进入了详情页,然后在详情页中删除了列表页中的某个选项,此时从详情页退回列表页时就要刷新,我们可以这样跳转:
1 this.$router.push({ 2 path: '/list', 3 query: { 'randomID': 'id' + Math.random() }, 4 })
这样的方案相对来说还是更简洁的。
五、多个请求下 loading 的展示与关闭
一般情况下,在 vue 中结合 axios 的拦截器控制 loading 展示和关闭,是这样的:
在 App.vue 配置一个全局 loading。
1 <div class="app"> 2 <keep-alive :include="keepAliveData"> 3 <router-view/> 4 </keep-alive> 5 <div class="loading" v-show="isShowLoading"> 6 <Spin size="large"></Spin> 7 </div> 8 </div>
同时设置 axios 拦截器
1 // 添加请求拦截器 2 this.$axios.interceptors.request.use(config => { 3 this.isShowLoading = true 4 return config 5 }, error => { 6 this.isShowLoading = false 7 return Promise.reject(error) 8 }) 9 10 // 添加响应拦截器 11 this.$axios.interceptors.response.use(response => { 12 this.isShowLoading = false 13 return response 14 }, error => { 15 this.isShowLoading = false 16 return Promise.reject(error) 17 })
这个拦截器的功能是在请求前打开 loading,请求结束或出错时关闭 loading。如果每次只有一个请求,这样运行是没问题的。但同时有多个请求并发,就会有问题了。
假如现在同时发起两个请求,在请求前,拦截器 this.isShowLoading = true 将 loading 打开。现在有一个请求结束了。this.isShowLoading = false 拦截器关闭 loading,但是另一个请求由于某些原因并没有结束。造成的后果就是页面请求还没完成,loading 却关闭了,用户会以为页面加载完成了,结果页面不能正常运行,导致用户体验不好。
解决方案
增加一个 loadingCount 变量,用来计算请求的次数。
现在拦截器变成这样:
1 // 创建loadingCount变量 2 let loadingCount = 0 3 // 添加请求拦截器 4 this.$axios.interceptors.request.use(config => { 5 this.isShowLoading = true 6 loadingCount++ 7 return config 8 }, error => { 9 this.isShowLoading = false 10 return Promise.reject(error) 11 }) 12 13 // 添加响应拦截器 14 this.$axios.interceptors.response.use(response => { 15 this.loadingCount-- 16 if (this.loadingCount == 0) { 17 this.isShowLoading = false 18 } 19 return response 20 }, error => { 21 this.isShowLoading = false 22 this.loadingCount = 0 23 return Promise.reject(error) 24 })
每当发起一个请求,打开 loading,同时 loadingCount 加 1。每当一个请求结束, loadingCount 减 1,并判断 loadingCount 是否为 0,如果为 0,则关闭 loading。这样即可解决,多个请求下有某个请求提前结束,导致 loading 关闭的问题。