脚本宝典收集整理的这篇文章主要介绍了

基于Vue实现后台系统权限控制

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。
<h3 id="articleHeader0">基于<a href="http://www.js-code.com/tag/vue" title="Vue" target="_blank">Vue</a>.js 2.x系列 + Element UI 的后台系统权限控制</h3> <blockquote> <h4>前言:关于vue权限路由的那些事儿……</h4> </blockquote> <p>项目背景:现有一个后台管理系统,共存在两种类型的人员</p> <p>①超级管理员(称作admin),②普通用户(称作editor)</p> <p>每种类型的人看到的操作栏并不一样,可以进行的操作也不尽相同,于是就需要程序处理一下各个权限问题。</p> <blockquote> <h4>过程说难不难,说简单不算简单</h4> </blockquote> <p><span class="img-wrap"><img data-src="/img/remote/1460000013472319?w=810&amp;h=571" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="vue权限" title="vue权限" style="cursor: pointer;"></span></p> <h5>【迷茫的前期】</h5> <p>上百度、Google,狂搜了好多关于权限的问题,也许是仁者见仁智者见智吧,五花八门的介绍让自己更加迷茫不堪,真心不知道从哪里下手:</p> <p>1)让后端返回关于权限的json数据吧,但却不太懂这样的数据应该怎样处理;</p> <p>2)在前端路由那里处理,可是不明白应该怎样使用何种属性来实现这个功能;</p> <h5>【最后】</h5> <p>最后看到一篇文章 <a href="https://juejin.im/post/591aa14f570c35006961acac" rel="nofollow noreferrer" target="_blank">手摸手,带你用vue撸后台 系列二(登录权限篇)</a><br />,但是发现代码非常多权限功能是整合在框架里面的,伤心,我就想实现一个小小的权限功能,没办法还是仔细的研究了起来。</p> <h3 id="articleHeader1">具体实现思路</h3> <p>1 创建vue实例的时候将vue-router挂载,但这个时候vue-router挂载一些登录或者不用权限的公用的页面。</p> <p>2 当用户登录后,获取用role,将role和路由表每个页面的需要的权限作比较,生成最终用户可访问的路由表。</p> <div class="google-auto-placed ap_container" style="text-align: center; width: 100%; height: auto; clear: none;"><ins data-ad-format="auto" class="adsbygoogle adsbygoogle-noablate" data-ad-client="ca-pub-6330872677300335" data-adsbygoogle-status="done" style="display: block; margin: auto; background-color: transparent;"><ins id="aswift_4_expand" style="display:inline-table;border:none;height:175px;margin:0;padding:0;position:relative;visibility:visible;width:697px;background-color:transparent;"><ins id="aswift_4_anchor" style="display:block;border:none;height:175px;margin:0;padding:0;position:relative;visibility:visible;width:697px;background-color:transparent;"><iframe width="697" height="175" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&amp;&amp;s.handlers,h=H&amp;&amp;H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&amp;&amp;d&amp;&amp;(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_4" name="aswift_4" style="left:0;position:absolute;top:0;border:0px;width:697px;height:175px;"></iframe></ins></ins></ins></div> <p>3 调用router.addRoutes(store.getters.addRouters)添加用户可访问的路由。</p> <p>4 使用vuex管理路由表,根据vuex中可访问的路由渲染侧边栏组件。</p> <p>&lt;font color=red size=4 face="黑体"&gt;是不是有点懵没关系下面我尽量用通俗点的话来讲每一步&lt;/font&gt;</p> <h3 id="articleHeader2">1在路由router.js里面声明权限为admin的路由(异步挂载的路由asyncRouter<a href="http://www.js-code.com/tag/map" title="Map" target="_blank">Map</a>)</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// router.js import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export const constantRouterMap = [ { path: '/', redirect: '/login', hidden: true }, { path: '/login', name: '登录页面', hidden: true, component: resolve => require(['../views/login/Login.vue'], resolve)<br /> },<br /> {<br /> path: '/Readme',<br /> // name: 'Readmehome',<br /> index: 'Readme',<br /> meta: {<br /> title: 'Readme',<br /> icon: 'el-icon-menu'<br /> },<br /> component: resolve => require(['../components/common/Home.vue'], resolve),<br /> children: [<br /> {<br /> name: 'Readme',<br /> path: '/',<br /> meta: { title: 'Readme', icon: 'el-icon-menu' },<br /> component: resolve => require(['../components/page/Readme.vue'], resolve)<br /> }<br /> ]<br /> }<br /> ]</p> <p>export default new Router({<br /> routes: constantRouterMap<br /> })<br /> // 异步挂载的路由<br /> // 动态需要根据权限加载的路由表<br /> export const asyncRouterMap = [<br /> {<br /> path: '/permission',<br /> // name: 'permissionhome',<br /> meta: {<br /> title: 'permission',<br /> icon: 'el-icon-setting',<br /> roles: ['admin']<br /> },<br /> component: resolve => require(['../components/common/Home.vue'], resolve),<br /> children: [<br /> {<br /> name: 'permission',<br /> path: '/permission',<br /> meta: {<br /> title: 'permission', icon: 'el-icon-menu', roles: ['admin']<br /> },<br /> component: resolve => require(['../components/page/permission.vue'], resolve)<br /> }<br /> ]<br /> },<br /> { path: '*', redirect: '/404', hidden: true }<br /> ]<br /> " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// router.js</span> <span class="hljs-keyword">import</span> <a href="http://www.js-code.com/tag/vue" title="浏览关于“Vue”的文章" target="_blank" class="tag_link">Vue</a> <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span> <span class="hljs-keyword">import</span> Router <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-router'</span> Vue.use(Router) <span class="hljs-keyword"><a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a></span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> constantRouter<a href="http://www.js-code.com/tag/map" title="浏览关于“Map”的文章" target="_blank" class="tag_link">Map</a> = [ { path: <span class="hljs-string">'/'</span>, redirect: <span class="hljs-string">'/login'</span>, hidden: <span class="hljs-literal">true</span> }, { path: <span class="hljs-string">'/login'</span>, name: <span class="hljs-string">'登录页面'</span>, hidden: <span class="hljs-literal">true</span>, component: <span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">require</span>([<span class="hljs-string">'../views/login/Login.vue'</span>], resolve) }, { path: <span class="hljs-string">'/Readme'</span>, <span class="hljs-comment">// name: 'Readmehome',</span> index: <span class="hljs-string">'Readme'</span>, meta: { title: <span class="hljs-string">'Readme'</span>, icon: <span class="hljs-string">'el-icon-menu'</span> }, component: <span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">require</span>([<span class="hljs-string">'../components/common/Home.vue'</span>], resolve), children: [ { name: <span class="hljs-string">'Readme'</span>, path: <span class="hljs-string">'/'</span>, meta: { title: <span class="hljs-string">'Readme'</span>, icon: <span class="hljs-string">'el-icon-menu'</span> }, component: <span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">require</span>([<span class="hljs-string">'../components/page/Readme.vue'</span>], resolve) } ] } ] <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">new</span> Router({ routes: constantRouterMap }) <span class="hljs-comment">// 异步挂载的路由</span> <span class="hljs-comment">// 动态需要根据权限加载的路由表</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> asyncRouterMap = [ { path: <span class="hljs-string">'/permission'</span>, <span class="hljs-comment">// name: 'permissionhome',</span> meta: { title: <span class="hljs-string">'permission'</span>, icon: <span class="hljs-string">'el-icon-setting'</span>, roles: [<span class="hljs-string">'admin'</span>] }, component: <span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">require</span>([<span class="hljs-string">'../components/common/Home.vue'</span>], resolve), children: [ { name: <span class="hljs-string">'permission'</span>, path: <span class="hljs-string">'/permission'</span>, meta: { title: <span class="hljs-string">'permission'</span>, icon: <span class="hljs-string">'el-icon-menu'</span>, roles: [<span class="hljs-string">'admin'</span>] }, component: <span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">require</span>([<span class="hljs-string">'../components/page/permission.vue'</span>], resolve) } ] }, { path: <span class="hljs-string">'*'</span>, redirect: <span class="hljs-string">'/404'</span>, hidden: <span class="hljs-literal">true</span> } ] </code></pre> <p>这里我们根据 <a href="https://router.vuejs.org/en/advanced/meta.html" rel="nofollow noreferrer" target="_blank">vue-router官方推荐</a> 的方法通过meta标签来标示改页面能访问的权限有哪些。如meta: { role: ['admin','super_editor'] }表示该页面只有admin和超级编辑才能有资格进入。</p> <p>注意事项:这里有一个需要非常注意的地方就是 404 页面一定要最后加载,如果放在<a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a>antRouter<a href="http://www.js-code.com/tag/map" title="Map" target="_blank">Map</a>一同声明了404,后面的所以页面都会被拦截到404,详细的问题见<a href="https://github.com/vuejs/vue-router/issues/1176" rel="nofollow noreferrer" target="_blank">addRoutes when you've got a wildcard route for 404s does not work</a></p> <h3 id="articleHeader3">2当用户登录后,获取用role,将role和路由表每个页面的需要的权限作比较,调用router.addRoutes(store.getters.addRouters)添加用户可访问的路由,生成最终用户可访问的路由表。路由表存在vuex里面</h3> <h3 id="articleHeader4">permission.js</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// permission.js import router from './router' import store from './store' import { Message } from 'element-ui' import { getToken } from '@/utils/auth' // 验权 const whiteList = ['/login', '/authredirect'] // 不重定向白名单 router.beforeEach((to, from, next) => {<br /> if (getToken()) { // 判断是否有token<br /> if (to.path === '/login') {<br /> next({ path: '/' })<br /> } else {<br /> if (store.getters.roles.length === 0) {<br /> console.log('roles====0')<br /> store.dispatch('GetInfo').then(res => { // 拉取用户信息<br /> const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']<br /> console.log('roles?', roles)<br /> store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表<br /> console.log('addrouters', store.getters.addRouters)<br /> router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表<br /> next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record<br /> })<br /> }).catch(() => {<br /> store.dispatch('FedLogOut').then(() => {<br /> Message.error('验证失败,请重新登录')<br /> next({ path: '/login' })<br /> })<br /> })<br /> } else {<br /> console.log('====1')<br /> next() // 当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面<br /> }<br /> }<br /> } else {<br /> if (whiteList.indexOf(to.path) !== -1) {<br /> next()<br /> } else {<br /> next('/login')<br /> }<br /> }<br /> })</p> <p>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// permission.js</span> <span class="hljs-keyword">import</span> router <span class="hljs-keyword">from</span> <span class="hljs-string">'./router'</span> <span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">'./store'</span> <span class="hljs-keyword">import</span> { Message } <span class="hljs-keyword">from</span> <span class="hljs-string">'element-ui'</span> <span class="hljs-keyword">import</span> { getToken } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/utils/auth'</span> <span class="hljs-comment">// 验权</span> <span class="hljs-keyword">const</span> whiteList = [<span class="hljs-string">'/login'</span>, <span class="hljs-string">'/authredirect'</span>] <span class="hljs-comment">// 不重定向白名单</span> router.beforeEach(<span class="hljs-function">(<span class="hljs-params">to, <span class="hljs-keyword">from</span>, next</span>) =&gt;</span> { <span class="hljs-keyword">if</span> (getToken()) { <span class="hljs-comment">// 判断是否有token</span> <span class="hljs-keyword">if</span> (to.path === <span class="hljs-string">'/login'</span>) { next({ path: <span class="hljs-string">'/'</span> }) } <span class="hljs-keyword">else</span> { <span class="hljs-keyword">if</span> (store.getters.roles.length === <span class="hljs-number">0</span>) { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'roles====0'</span>) store.dispatch(<span class="hljs-string">'GetInfo'</span>).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> { <span class="hljs-comment">// 拉取用户信息</span> <span class="hljs-keyword">const</span> roles = res.data.roles <span class="hljs-comment">// note: roles must be a array! such as: ['editor','develop']</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'roles?'</span>, roles) store.dispatch(<span class="hljs-string">'GenerateRoutes'</span>, { roles }).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { <span class="hljs-comment">// 根据roles权限生成可访问的路由表</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'addrouters'</span>, store.getters.addRouters) router.addRoutes(store.getters.addRouters) <span class="hljs-comment">// 动态添加可访问路由表</span> next({ ...to, replace: <span class="hljs-literal">true</span> }) <span class="hljs-comment">// hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record</span> }) }).catch(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { store.dispatch(<span class="hljs-string">'FedLogOut'</span>).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { Message.error(<span class="hljs-string">'验证失败,请重新登录'</span>) next({ path: <span class="hljs-string">'/login'</span> }) }) }) } <span class="hljs-keyword">else</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'====1'</span>) next() <span class="hljs-comment">// 当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面</span> } } } <span class="hljs-keyword">else</span> { <span class="hljs-keyword">if</span> (whiteList.indexOf(to.path) !== <span class="hljs-number">-1</span>) { next() } <span class="hljs-keyword">else</span> { next(<span class="hljs-string">'/login'</span>) } } }) </code></pre> <h3 id="articleHeader5">3使用vuex管理路由表,根据vuex中可访问的路由渲染侧边栏组件(菜单)。</h3> <p><span class="img-wrap"><img data-src="/img/remote/1460000013472320?w=1104&amp;h=732" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="sidebar" title="sidebar" style="cursor: pointer;"></span></p> <h2 id="articleHeader6">最后预览链接</h2> <p><a href="https://mgbq.github.io/vue-permission/#/login" rel="nofollow noreferrer" target="_blank">vue实现的权限系统</a></p> <h2 id="articleHeader7">源码下载</h2> <p><a href="https://github.com/mgbq/vue-permission" rel="nofollow noreferrer" target="_blank">https://github.com/mgbq/vue-p...</a></p> <h2 id="articleHeader8">打赏 衷心的表示感谢</h2> <p><span class="img-wrap"><img data-src="/img/remote/1460000013472321?w=425&amp;h=425" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="打赏" title="打赏" style="cursor: pointer;"></span></p> <h2 id="articleHeader9">最后如有不对的麻烦指正</h2>

总结

以上是脚本宝典为你收集整理的

基于Vue实现后台系统权限控制

全部内容,希望文章能够帮你解决

基于Vue实现后台系统权限控制

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过