思路:前端
按鈕權限也能夠用v-if判斷,可是若是頁面過多,每一個頁面頁面都要獲取用戶權限role和路由表裏的meta.btnPermissions,而後再作判斷,感受有點麻煩,而自定義指令,只需在權限按鈕加入該指令便可。vue
路由配置:node
path: '/permission', component: Layout, name: '權限測試', meta: { btnPermissions: ['admin','supper','normal'] }, //頁面須要的權限 children: [ { path: 'supper', component: _import('system/supper'), name: '權限測試頁', meta: { btnPermissions: ['admin','supper'] } //頁面須要的權限 }, { path: 'normal', component: _import('system/normal'), name: '權限測試頁', meta: { btnPermissions: ['admin'] } //頁面須要的權限 } ]
注:若是按鈕的權限是由後臺配置並返回的此處可不設置,從後臺獲取權限便可後端
自定義指令:數組
import Vue from 'vue' /**權限指令**/ const has = Vue.directive('has', { bind: function (el, binding, vnode) { // 獲取按鈕權限 let btnPermissions = vnode.context.$route.meta.btnPermissions.split(","); if (!Vue.prototype.$_has(btnPermissions)) { el.parentNode.removeChild(el); } } }); // 權限檢查方法 Vue.prototype.$_has = function (value) { let isExist = false; let btnPermissionsStr = sessionStorage.getItem("btnPermissions"); if (btnPermissionsStr == undefined || btnPermissionsStr == null) { return false; } if (value.indexOf(btnPermissionsStr) > -1) { isExist = true; } return isExist; }; export {has}
而後在main.js文件引入文件session
import has from './public/js/btnPermissions.js';
頁面中按鈕只需加v-has便可post
<el-button @click='editClick' type="primary" v-has>編輯</el-button>
權限先後端均可進行控制,可是儘量的在前端就進行攔截驗證。借用一句經典名言:永遠不相信用戶輸入!測試