一、用户权限
1. 修改router/index.js文件
去掉多余的路由,只留下这两个路由。/404、{ path: “*”, redirect: “/404”, hidden: true }都注释掉。
import { adminMenus, signUserMenus } from "@/router/menus";
const getDefaultState = () => {
return {
menus: "", // 存放路由表
};
};
const mutations = {
SET_MEUN: (state, menus) => {
state.menus = menus;
},
}
// 如果是后端返回的路由结构,在这个里面导入
getRouter({ commit, state }) {
return new Promise((resolve, reject) => {
let role = sessionStorage.getItem("name");
let menus;
if (role == "admin") {
menus = adminMenus;
} else if (role == "urgent") {
menus = urgentMenus;
} else {
menus = signUserMenus;
}
// 动态添加404
menus.push(
{
path: "/404",
component: "404",
hidden: true,
},
{
path: "*",
redirect: "/404",
hidden: true,
}
);
commit("SET_MEUN", menus);
resolve();
});
},
3. 修改store/getters.js文件
const getters = {
menus: (state) => state.user.menus,
};
4. 自定义路由结构文件
因为路径在前端就定死了,所以就在前端写了个路由文件menus.js。
// 自定义admin的路由结构,一级路由、二级路由
export const adminMenus = [
{
component: "Layout",
hidden: false,
path: "/operation",
children: [
{
path: "index",
component: "operation/index",
name: "operation",
meta: { title: "许可", icon: "operation" },
},
],
},
{
alwaysShow: true,
component: "Layout",
hidden: false,
path: "/system",
meta: {
title: "系统管理",
icon: "system",
},
children: [
{
hidden: false,
title: "用户管理",
path: "user",
component: "user/index",
name: "user",
meta: {
title: "用户管理",
icon: "el-icon-user",
},
}
],
},
5、新建两个路由加载文件
_import_development.js
// 开发环境导入组件
module.exports = file => require('@/views/' + file + '.vue').default
_import_production.js
// 生产环境导入组件
module.exports = file => () => import('@/views/' + file + '.vue')
import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
const _import = require("./router/_import_" + process.env.NODE_ENV); // 获取组件的方法
import Layout from "@/layout";
NProgress.configure({ showSpinner: false }); // NProgress Configuration \ n程序配置
const whiteList = ["/login"]; // 白名单中的重定向
router.beforeEach(async (to, from, next) => {
// 启动进度条
NProgress.start();
// 设置页面标题
document.title = getPageTitle(to.meta.title);
// 确定用户是否已登录
const hasToken = getToken();
let token = sessionStorage.getItem("token");
if (token) {
if (to.path === "/login") {
// 如果已登录,请重定向到主页
next({ path: "/" });
NProgress.done();
} else {
const hasGetUserInfo = store.getters.name;
if (hasGetUserInfo) {
next();
} else {
try {
// 获取用户信息
await store.dispatch("user/getInfo");
// 请求路由表
await store.dispatch("user/getRouter");
// 判断路由表的长度
if (store.getters.menus.length < 1) {
global.antRouter = [];
next();
}
const menus = filterAsyncRouter(store.getters.menus); // 过滤路由
// 动态添加路由
router.addRoutes(menus);
// 将路由数据传递给全局变量,做侧边栏渲染的工作
global.antRouter = menus;
next({ ...to, replace: true });
// next();
} catch (error) {
// 删除令牌并转到登录页面重新登录
await store.dispatch("user/resetToken");
Message.error(error || "Has Error");
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
}
} else {
/* 没有token*/
if (whiteList.indexOf(to.path) !== -1) {
// 在免费登录白名单中,直接进入
next();
} else {
// 没有访问权限的其他页面将重定向到登录页面。
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
});
router.afterEach(() => {
// 完成进度条
NProgress.done();
});
// 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
const accessedRouters = asyncRouterMap.filter((route) => {
if (route.component) {
if (route.component === "Layout") {
route.component = Layout;
} else {
try {
route.component = _import(route.component); // 导入组件
} catch (error) {
// route.component = _import('home/index') // 导入组件
// Message.error("请查看控制台修改或者删除不存在的组件路径"); // 弹出异常('请修改或者删除不存在的组件路径')
}
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children);
}
return true;
});
return accessedRouters;
}
二、按钮权限
main.js
import '@/permission' // 权限控制
// 自定义指令 按钮权限
Vue.directive('permissions', {
// 当被绑定的元素插入到 DOM 中时……
inserted(el, binding, node) {
const {
value
} = binding
// const roles = node.child.$route.meta.roles
// 获取到当前用户的权限结构
const roles = JSON.parse(sessionStorage.getItem('authorities'));
// console.log(roles)
// console.log(node.child.$route)
// if (roles.indexOf(value) >= 0) {
// return value
// } else {
// el.parentNode && el.parentNode.removeChild(el)
// } //使用方式: v-permission="'add'"
if (value && value instanceof Array && value.length > 0) {
const permissionRoles = value
const hasPermission = roles.some(role => {
return permissionRoles.includes(role)
})
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error(`使用方式: v-permission="['admin','editor']"`)
}
}
})
index.vue
<el-button
type="primary"
@click="pageQuery('cx')"
v-permissions="findOrgPage"
>查询el-button
>
data(){
retunr{
findOrgPage: ["findOrgPage"],
}
}