VUE 動態(tài)菜單及視圖權(quán)限

動態(tài)菜單

這幾天在做VUE的動態(tài)菜單及權(quán)限,參考了下:

https://segmentfault.com/a/1190000015419713?utm_source=tag-newest

然后發(fā)現(xiàn)和我的需求還是有點(diǎn)不符:上面的作者是整個權(quán)限都是從接口拉下來的
而我的需求是:原來有一部分權(quán)限,然后從接口獲取另外一部分權(quán)限,PUSH到現(xiàn)有權(quán)限中
所以對作者的GIT代碼進(jìn)行了修改,原來的權(quán)限:

const vueRouter = new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '*',
      component: error404
    },
    {
      path: '/manage',
      name: '首頁',
      component: Manage,
      meta: { title: '首頁' },
      children: [
          {
          path: 'home',
          component: Home,
          meta: { title: '首頁' }
        }
      ]
    },
    {
      path: '/404',
      name: '出錯了',
      component: error404
    }
  ]
  //路由樣式
  // linkActiveClass: "active-router",
  // linkExactActiveClass: "exact-router"
})

主要修改的是permission.js

import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import axios from 'axios'
const _import = require('@/router/_import_' + process.env.NODE_ENV)//獲取組件的方法
import Layout from '@/page/manage' //Layout 是架構(gòu)組件,不在后臺返回,在文件里單獨(dú)引入
import { getToken } from '@/utils/auth' // getToken from cookie


router.beforeEach((to, from, next) => {
  console.log("====beforeEach====")
  if (getToken()) { //如果用戶已經(jīng)登錄
    if (to.path === '/login') {
      next()
      // NProgress.done() // if current page is dashboard will not trigger  afterEach hook, so manually handle it
    } else {
      if (store.getters.getMenu.length === 0) {
        store.dispatch('GetUserInfo').then(res => {
          var getRouter = res.data.router//后臺拿到路由
          routerGo(to, next, getRouter)//執(zhí)行路由跳轉(zhuǎn)方法
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            // Message.error(err || 'Verification failed, please login again')
            console.log(err)
            next({ path: '/login' })
          })
        })
      } else {
        next();
        }
      }
    }
  } else {
    if (to.path == '/login') {//如果是登錄頁面路徑,就直接next()
      next();
    } else {//不然就跳轉(zhuǎn)到登錄;
      next('/login');
    }
  }
})


function routerGo(to, next, getRouter) {
  getRouter = filterAsyncRouter(getRouter) //過濾路由
  getRouter.map(v => { router.options.routes.push(v) })//將接口獲取到的路由push到現(xiàn)有路由中
  router.addRoutes(getRouter)//動態(tài)添加路由
  global.antRouter = router.options.routes //將路由數(shù)據(jù)傳遞給全局變量,做側(cè)邊欄菜單渲染工作
  next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace:
}

function filterAsyncRouter(asyncRouterMap = []) { //遍歷后臺傳來的路由字符串,轉(zhuǎn)換為組件對象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {//Layout組件特殊處理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}

關(guān)鍵是這句getRouter.map(v => { router.options.routes.push(v) })//將接口獲取到的路由push到現(xiàn)有路由中
如果你想加入到現(xiàn)有router的某個節(jié)點(diǎn)的children里 可以這樣:
router.options.routes[0].children.push()
這里還要注意的是 beforeEach會出現(xiàn)死循環(huán)
因為next({ path: '/login' })next方法加了參數(shù) 就又會走一次beforeEach方法 如果是next()就不會
可以這樣處理:

if (to.path == '/login') {//如果是登錄頁面路徑,就直接next()
      next();
    } else {//不然就跳轉(zhuǎn)到登錄;
      next('/login');
    }

視圖權(quán)限

也就是按鈕級別的權(quán)限。原理很簡單,利用router的meta字段

{
        "path": "/system",
        "component": "Layout",
        "redirect": "/system/userList",
        "name": "系統(tǒng)管理",
        "meta": {
          "title": "系統(tǒng)管理",
          "icon": "el-icon-setting"
        },
        "children": [{
          "path": "userList",
          "name": "用戶列表",
          "component": "user/index",
          "meta": {
            "title": "用戶列表",
            "icon": "el-icon-tickets",
            "permission": ['add'] //按鈕權(quán)限
          }
        }
  ]
}

meta.permission字段里放入的是該用戶在此頁面能操作的按鈕權(quán)限的標(biāo)識,比如這個頁面有add、edit、delele權(quán)限,但是你只想讓這個用戶使用add,那么就"permission": ['add']

接著自定義指令btnPermission.js,在mian.js導(dǎo)入

import Vue from 'vue'

/**權(quán)限指令**/
Vue.directive('has', {
    inserted: function (el, binding, vnode) {
        let permissionList = vnode.context.$route.meta.permission;
        if (!permissionList || !permissionList.includes(binding.value.role)) {
            el.parentNode.removeChild(el)
        }
    }
})
export { has }

如何使用:

<el-button type="success" icon="el-icon-circle-plus-outline" @click="handeleAdd" v-has="{role : 'add'}">添加</el-button>

這里要注意vue2.0 自定義指令 v-has="{role : 'add'}"參數(shù)必須要傳入對象 否則會無效

具體代碼我上傳到了GIT:https://github.com/yoolika/admin-manage

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容