什么后台管理权限
vue如何控制用户的权限
我们是这样做的,用户登录后,后台会返回这个用户的权限,比如用字段auth表示,我们就根据这个auth字段
从我们实现创建好的路由表中,找到符合其权限的路由表,然后利用this.$router.addRoutes将其
对应的路由表动态添加,这样接可以得到不同用户权限的路由了
权限的目得就是防止一些用户的违规操作,不同的用户就有不同的权限 注意addRoutes([]) 里边是参数是一个数组
正常权限为三种: 接口权限 路由菜单权限 按钮权限
搭建后台服务器(这里我使用express)
yarn init -y
yarn add express
const express = require("express")
const app = new express();
const host = "3000";
app.get("/user",(req,res) => {
let response = {
code: 200,
token: 'jdqd11 dqwdqwdeq awdqawdqewq',
auth: ["user"]
}
res.send(response)
})
app.listen(host,()=> {
console.log("service启动" + " " + 'http://localhost:' + host);
})
启动是 node index.js
后端url地址: http://localhost:3000
搭建vue项目
npx vue create permission
yarn add axios
yarn add vuex
yarn add router
整个vue项目文件入下图所示:
在router文件下新建常规路由 index.js,在router.beforeEach前置守卫这里边进行路由拦截
- 引入
import Vue from 'vue'
import VueRouter from 'vue-router';
import Store from '../store';
Vue.use(VueRouter)
let whiteList = ["/"] ; // 登录页面
const routes = [
{
path:'/',
name: 'login',
component: () => import("../views/login.vue")
},
]
const router = new VueRouter({
routes
})
router.beforeEach(async (to,from,next) => {
let token = localStorage.getItem("token");
let auth = Store.state.permission.auth;
if(token) {
if(auth.length === 0) {
let roles = await Store.dispatch("permission/actionAuth")
if(roles.length) {
let filterRoutes = await Store.dispatch("permission/createRoutes",roles)
console.log("filterRoutes",filterRoutes);
router.addRoutes(filterRoutes)
next({...to,replace: true}) // 防止 addRoutes添加过慢,造成的页面白屏 //
} else { // 如果后端真没有数据,直接返回登录也买你
next(`/?url=${to.fullPath}`)
}
} else {
next()
}
} else {
if(whiteList.indexOf(to.path)!=-1) {
next()
} else {
next(`/?url=${to.fullPath}`)
}
}
})
export default router
在router文件下新建动态路由 permission.js
// const Demo1 = () => import("../views/Demo1.vue")
const Demo2 = () => import("../views/Demo2.vue")
const Demo3 = () => import("../views/Demo3.vue")
const Demo4 = () => import("../views/Demo4.vue")
const Demo5 = () => import("../views/Demo5.vue")
const Demo6 = () => import("../views/Demo6.vue")
import Demo1 from '../views/Demo1.vue'
// 每个都是携带这个user的和admin的,还有一种写法就是后端直接返回一个 ['administration'] 直接 把 const rotutes = asyncRoutes
// 其它的就是 根据 filter 加上 some 和 includes结合判断,动态添加在 this.$router.addRoutes(a)
export const asyncRoutes = [
{
path: '/demo1',
name: 'Demo1',
meta: {
roles: ['admin','user']
},
component: Demo1,
children: [
{
path: '/demo6',
name: 'Demo6',
meta: {
roles: ['admin','user']
},
component: Demo6
}
],
},
{
path: '/demo2',
name: 'Demo2',
meta: {
roles: ['admin']
},
component: Demo2
},
{
path: '/demo3',
name: 'Demo3',
meta: {
roles: ['admin','user']
},
component: Demo3
},
{
path: '/demo4',
name: 'Demo4',
meta: {
roles: ['admin','user']
},
component: Demo4
},
{
path: '/demo5',
name: 'Demo5',
meta: {
roles: ['admin']
},
component: Demo5
},
{ // 404所有的人都可以访问
path: '*',
name: '404',
meta: {
roles: ['admin',"user"]
},
component: () => import("../views/404.vue")
}
]
新建store文件夹,在store文件下新建modules文件夹和index.js,在modules文件下新建permission.js
- permissions.js
import axios from '../../../fetch/index';
import {asyncRoutes} from '../../router/permission';
export default {
namespaced: true,
state: {
auth: [],
token: "" || localStorage.getItem("token"),
routes: []
},
getters: {
},
mutations: {
setAuth(state,auth) {
state.auth = auth;
},
setToken(state,token) {
state.token = token;
localStorage.setItem("token",token)
},
setRoutes(state,routes) {
console.log("routes",routes);
state.routes = routes;
}
},
actions: {
// 拿到后台管理权限的数据
actionAuth({commit}) {
return new Promise((resolve,reject) => {
axios.get("user").then(res => {
let { code, auth,token } = res.data;
if(code === 200) {
commit("setAuth",auth)
commit("setToken",token)
resolve(auth)
}
}).catch(err=> {
reject(err)
})
})
},
// 过滤角色
async createRoutes({commit},roles) {
console.log("roles",roles);
return new Promise((resolve,reject) => {
if(roles.length) {
let res = asyncRoutes.filter(item => {
return item.meta.roles.some(role => {
return roles.includes(role)
})
})
commit("setRoutes",res)
resolve(res)
} else {
reject("err")
}
})
}
}
}
- index.js
import Vue from 'vue'
import Vuex from 'vuex'
import permission from './modules/permission';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
permission
}
})
新建fetch文件夹,在featch文件夹下新建index.js和api.js
- api.js
const api = {
user: {
name: '用户权限',
url: '/user'
}
}
export default api
- index.js
import axios from 'axios'
import api from '../fetch/api'
const newAxios = axios.create({
// 公共的请求url地址
baseURL:process.env.VUE_APP_API,
timeout: 60000
})
newAxios.interceptors.request.use(config => {
console.log("config",config.url);
config.url = api[config.url].url
return config
},error=> {
Promise.reject(error)
})
newAxios.interceptors.response.use(res => {
// 在这里边一般处理响应的状态的结果,比如 200 403 404等等
return res
},error=> {
Promise.reject(error)
})
export default newAxios
新建vue.config.js 前端处理后端跨域问题
- vue.config.js
module.exports = {
devServer: {
proxy: {
"/api": {
target: 'http://localhost:3000/', // target代理的就是后端的接口地址
changeOrigin: true, // 是否允许跨域,默认就为true
// secure: false, // 如果是https接口,需要配置这个参数
pathRewrite: {
"^/api": ""
}
}
}
}
}
login.vue进行登录
<template>
<div class="login">
<button @click="login">登录</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
data() {
return {
}
},
methods: {
...mapActions("permission",["actionAuth"]),
login() {
this.actionAuth().then(res => {
let path = this.$route.query.url || '/demo1' // 默认demo1是登录后的首页
console.log("path",path)
this.$router.push(path)
})
}
},
created() {}
}
</script>
<style>
</style>
附加:按钮权限实现
- 新建utils文件夹 新建directive.js
import Vue from 'vue';
import Store from '../store';
Vue.directive('Auth', {
// 当被绑定的元素插入到 DOM 中时……
inserted: (el, binding) => {
const value = binding.value;
const auths = Store.state.permission.auth;
if(auths.length) {
let flag = value.some((item => auths.includes(item)))
console.log("flag",flag);
if(!flag) {
el.parentNode.removeChild(el); // 如果不存在就删除掉
}
}
}
});
- main.js引入 directive.js
import Vue from 'vue'
import App from './App.vue'
import store from './store';
import router from './router';
Vue.config.productionTip = false
import axios from '../fetch/index';
Vue.prototype.$axios = axios
import './util/directive.js';
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
在demo3.vue中
<template>
<div>demo4
<button v-Auth="['admin']">admin按钮</button>
<button v-Auth="['admin','user']">user按钮</button>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>