在业务中经常会遇到权限管理的问题,例如按钮级别或者页面内操作权限的需求,我们可以编写一个全局自定义指令。例如我们可以将指令直接注册到 main.js
中:
import Vue from "vue";
import App from "./App.vue";
Vue.directive("auth-key", {
inserted(el, binding) {
// ...
}
})
new Vue({
render: h => h(App),
}).$mount("#app");
这样的缺点就是无法复用,例如我们希望把这个指令用到别的项目中,就需要手动复制粘贴。为避免这种情况,我们可以将这个指令封装为 Vue 插件,这样可以作为 npm 包发布。一个典型的 Vue 插件范式如下:
const authPlugin = {
install (app, options) {
app.directive('auth-key', {
// install 方法的第一个参数可以拿到 Vue 构造器
// 这块可以参考 Vue.use 源码
})
}
}
export default authPlugin
结合上面的插件,编写一个权限指令如下:
function checkArray(key) {
let arr = [1, 2, 3, 4];
return arr.includes(key);
}
const authPlugin = {
install (app, options) {
app.directive('auth-key', {
inserted(el, binding) {
let displayKey = binding.value;
if (displayKey) {
let hasPermission = checkArray(displayKey);
if (!hasPermission) {
// 访问到父节点,通过父节点移除当前节点
el.parentNode && el.parentNode.removeChild(el);
}
}
}
})
}
}
export default authPlugin
在页面中使用:
<button v-auth-key="8">Click me!</button>