// directive/permission/permission.js
import router from '@/router'
export default {
inserted(el, binding, vnode) {
const { value } = binding
if (value && value instanceof Array && value.length > 0) {
const currentRoute = router.currentRoute
const hasPermission = value.includes(currentRoute.meta.permission)
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
theow new Error(`need operate permissions! Like v-permission="[1,2]"`)
}
}
}
// directive/permission/index.js
import permission from './permission'
const install = function(Vue) {
Vue.directive('permission', permission)
}
if (window.Vue) {
window['permission'] = permission
Vue.use(install)
}
permission.install = install
export default permission
// main.js
import permission from '@/directive/permission/index.js'
Vue.use(permission)
<template>
<el-tag v-permission="[1, 2]">admin</el-tag>
</template>
In some cases it is not suitable to use v-permission, such as element Tab component which can only be achieved by manually setting the v-if.
// utils/permission.js
import router from '@/router'
export default function checkPermission(value) {
if (value && value instanceof Array && value.length > 0) {
const currentRoute = router.currentRoute
return value.includes(currentRoute.meta.permission)
} else {
console.error(`need operate permissions! Like v-permission="[1,2]"`)
return false
}
}
<template>
<el-tag v-if="checkPermission([1, 2])">admin</el-tag>
</template>