Vue3 自定义指令实现按钮权限控制
业务需求除了路由需要控制外点击按钮也需要做到控制,百度了vue2相关资料发现大部分都是使用自定义指令实现控制按钮显示和隐藏,刚好手头上做了个demo 写个文档记录下;vue2和vue3directive的函数也不一样bind → beforeMountinserted → mountedbeforeUpdate: new! this is called before the element its
·
业务需求除了路由需要控制外点击按钮也需要做到控制,百度了vue2相关资料发现大部分都是使用自定义指令实现控制按钮显示和隐藏,刚好手头上做了个demo 写个文档记录下;
vue2和vue3directive的函数也不一样
bind → beforeMount
inserted → mounted
beforeUpdate: new! this is called before the element itself is updated, much like the component lifecycle hooks.
update → removed! There were too many similarities to updated, so this is redundant. Please use updated instead.
componentUpdated → updated
beforeUnmount: new! similar to component lifecycle hooks, this will be called right before an element is unmounted.
unbind -> unmounted
前置条件
首先路由的meta中需要包含按钮的权限信息方便获取;例如:
新建一个vuex模块或者新建一个reactive响应式文件存储值
在Layout里存储权限值(Layout是所有路由视图的公共组件)
...
import { useStore } from "vuex";
import { useRoute } from 'vue-router'
...
export default {
setup() {
const store = useStore();
const $route = useRoute();
watchEffect(() => {
const { add, edit, detail, del, more } = $route.meta;
const role = { add, edit, detail, del, more };
for(const item in role) {
store.commit('role/setRole', { name: item, type :role[item] })
}
}
}
}
注册全局指令
在main.js中输入
...
import store from './store'
const app = createApp(App);
app.directive('permission', {
mounted(el, binding) {
if (!store.state.role[binding.value]) {
el.parentNode && el.parentNode.removeChild(el)
}
}
}
...
在需要用到控制权限的button按钮上输入
<a-button v-permission="'add'" type="primary" @click="onSubmit">确 定</a-button>
就可以轻松实现按钮的控制了
参考资料:
vue 官方文档
vue3 directive挂载生命周期
directive el.parentNode为null的相关处理
更多推荐
所有评论(0)