此次项目需要用到权限管理的一些知识,就去网上看了些,再结合自己的实际修改了部分,实现了无权限不能访问特殊路径这一功能,特此记录
首先在src文件夹中编辑这样的结构
在这里插入图片描述
main.js中引入 router 与 store

import router from './router'
import store from './store'
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

store.js 中 编写vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  //存储用户权限信息,初始时为空
  roles: ''
}

const getters = {
  getRoles: state => state.roles,
}

const mutations = {
  //添加用户权限,如果存在,不添加
  addRoles(state,{roles}) {
    state.roles = roles;
    console.log(state.roles);
  }
}

const actions = {
  addRoles:({commit},{roles}) =>{
    commit('addRoles',{roles});
  }
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

router.js 中 编写路径 如果不需要添加权限限制,可以不用加meta

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let routerMap = [
    {path: '/login',component: resolve => require(['./views/login.vue'], resolve)},
    {path: '/home',component: resolve => require(['./views/Home.vue'], resolve),name:'home',meta:1},
    {path: '/about',component: resolve => require(['./views/About.vue'], resolve),name:'about',meta:2},
    {path: '/see',component: resolve => require(['./views/see.vue'], resolve),name:'see',meta:3}
    ]


    let route =  new Router({
      routes: routerMap
    })
    
    route.beforeEach((to, from, next) => {
      //获取用户权限信息,为空即没登录,跳转至登录页
      if (to.path === '/login') {
        next();
      } else {
        //获取store中数据roles
        let role = route.app.$options.store.state.roles; 
        if (role === '') {
          next('/login');
        } else {
         //通过indexOf判断 role中是否包含meta 从而确定是否跳转
          if(role.indexOf(to.matched[0].meta) > -1) { 
            next();
          } else {
            next('此处可以设置为跳转首页');
          }
        }
      }
    });
    export default route;

权限设置时(此处设置的固定值,理应为后台传回的数据)

if(this.login_name==123456&&this.login_pwd==123456){
        this.$store.commit('addRoles',{
         //此处赋予了此用户'/about', '/home'的访问权限,而限制了‘/see’的访问权限
          roles:[1,2]
        });
      }else{
        alert("账号密码有误");
      }

设置完成后,每跳转路径,都会经过判断来决定 显示 或者 跳转 /login

Logo

前往低代码交流专区

更多推荐