原生elementUI中的el-tree树形控件在点击子树后是不能获取到父节点的,需要改变其源码才行
javascript
vue elementUI tree树形控件获取父节点ID的实例
修改源码:
情况1: element-ui没有实现按需引入打包
node_modules\element-ui\lib\element-ui.common.js 25382行修改源码 去掉 'includeHalfChecked &&'
// if ((child.checked || includeHalfChecked && child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
if ((child.checked || child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
情况2: element-ui实现了按需引入打包
node_modules\element-ui\lib\tree.js 1051行修改源码 去掉 'includeHalfChecked &&'
// if ((child.checked || includeHalfChecked && child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
if ((child.checked || child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
展示相应按钮
- 使用vuex管理权限
javascript
// store/modules/user.js
const state = {
permissions: [] // 权限列表,例如 ['VIEW_DASHBOARD', 'EDIT_PROFILE']
};
const mutations = {
SET_PERMISSIONS(state, permissions) {
state.permissions = permissions;
}
};
const actions = {
fetchPermissions({ commit }) {
// 这里模拟从服务器获取权限
const permissions = ['VIEW_DASHBOARD', 'EDIT_PROFILE'];
commit('SET_PERMISSIONS', permissions);
}
};
const getters = {
hasPermission: (state) => (permission) => {
return state.permissions.includes(permission);
}
};
export default {
state,
mutations,
actions,
getters
};
- 在组件中根据权限显示按钮
javascript
<template>
<div>
<button v-if="hasPermission('EDIT_PROFILE')">Edit Profile</button>
<button v-if="hasPermission('VIEW_DASHBOARD')">View Dashboard</button>
</div>
</template>
<script>
export default {
computed: {
hasPermission() {
return this.$store.getters.hasPermission;
}
}
};
</script>
- 通过全局指令展示按钮
可以创建一个自定义指令来根据权限动态显示或隐藏元素。
a. 创建自定义指令
javascript
export default {
install(Vue) {
Vue.directive('permission', {
bind(el, binding, vnode) {
const permissions = binding.value;
const userPermissions = vnode.context.$store.getters.permissions; // 从 Vuex 获取权限
if (!permissions.some(permission => userPermissions.includes(permission))) {
el.parentNode && el.parentNode.removeChild(el);
}
}
});
}
};
b. 在main.js中注册
javascript
import PermissionDirective from './directives/permission';
Vue.use(PermissionDirective);
c. 在组件中使用
javascript
<template>
<div>
<button v-permission="['EDIT_PROFILE']">Edit Profile</button>
<button v-permission="['VIEW_DASHBOARD']">View Dashboard</button>
</div>
</template>