利用vuex和localStorage实现vue菜单权限管理(笔记)

最近需要实现菜单权限管理的功能,好久没写了,之前也没有记录过,就很烦。在这里记录一下。实现方法太多了。后续再整理一下。

store/index.js

vuex里获取权限列表

//存token
const state = {
  Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '',
}

const mutations = {
  setMenu: (state, data) => {
    state.menuList = data
  },
  setList: (state, data) => {
    state.routerList = data
  },
  changeLogin: (state, user) => {
    state.Authorization = user.Authorization;
    localStorage.setItem('Authorization', user.Authorization);
  }
};

const actions = {
  // 获取权限列表
  getPermission({commit}) {
    return new Promise((resolve, reject) => {
      axios({
        url: '/api/user?id=' + localStorage.getItem('Authorization'),
        methods: 'get',
        data: {
          "token": localStorage.getItem('Authorization'),
        }
      }).then((res) => {
        // 存储权限列表
        commit('setList', res.data.data.routerLsit);
        commit('setMenu', res.data.data.menuList);
        resolve(res.data.data.routerLsit)
      }).catch(() => {
        reject()
      })
    })
  }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
});
 
export default store;

router/index.js的 router.beforeEach

  store.dispatch('getPermission').then((res) => { //获取有权限的路由列表
        // console.log("路由列表",store.state.routerList);
        // console.log("菜单列表",store.state.menuList);
        var routers = [...store.state.routerList];
        for (let router of routers) {
          let component = components[router.component];
          router.component = component;
        }
        router.addRoutes(routers);
  })

或者

store/index.js

const actions = {}   //咱们在router.beforeEach里实现vuex储存权限列表,这里就不需要了

router/index.js

路由守卫里 router.beforeEach 获取权限列表存到vuex里

    axios({
          url: '/api/user?id=' + localStorage.getItem('Authorization'),
          methods: 'get',
          data: {
            "token": localStorage.getItem('Authorization'),
          }
      }).then((res) => {
          // 存储权限列表
          store.commit('setList', res.data.data.routerLsit);
          store.commit('setMenu', res.data.data.menuList);
          // resolve(res.data.data.routerLsit)
      }).then(() => {
          var routers = [...store.state.routerList];
          for (let router of routers) {
            let component = components[router.component];
            router.component = component;
          }
          router.addRoutes(routers);
      })

最后页面中从vuex中拿到菜单列表

import {mapState} from "vuex"

computed: {
    ...mapState({
         menuList:state=>state.menuList
    })
},
mounted(){
     console.log(this.menuList)
}

这篇文章纯属笔记,有兴趣的朋友可以自己了解一下localstorage,sessionstorage, vuex

发表评论

电子邮件地址不会被公开。 必填项已用*标注