vue封装一个简单的权限管理功能, 控制页面的按钮显示与隐藏
1、在项目入口html文件创建全局变量
<head><script>// 创建全局变量window.SITE_CONFIG = {};// 登录成功后获取到的按钮权限数据存储到这里window.SITE_CONFIG['purview'] = [];</script>
</head>
2、在utils/index.js里编写
export function hasPurview(key) {return window.SITE_CONFIG['purview'].indexOf(key) !== -1 || false
}
3、在main.js里引入
import {hasPurview} from '@/utils/index.js'
Vue.prototype.$hasPurview = hasPurview;
4、在页面使用
<el-button v-if="$hasPurview('add')">提交</el-button>
5、模拟获取到的权限数据
axios.post('接口地址').then(({data:res})=>{if (res.data !== 200){return this.$message.error(res.msg)}// 返回值数据: res.data.purview = ['add','del','update']window.SITE_CONFIG['purview'] = res.data?.purview;
})