auth.ts 1.05 KB
/**
 * 权限指令
 * 使用方式:v-auth="'system:user:add'" 或 v-auth="['system:user:add', 'system:user:edit']"
 */

import type { Directive } from "vue";

import { useUserStore } from "@/stores";

export const auth: Directive = {
	mounted(el, binding) {
		const { value } = binding;
		const userStore = useUserStore();

		if (!value) return;

		const authorities = Array.isArray(value) ? value : [ value ];
		const hasPermission = userStore.hasAuthority(authorities);

		if (!hasPermission) {
			el.remove();
		}
	},
	updated(el, binding) {
		const { value } = binding;
		const userStore = useUserStore();

		if (!value) return;

		const authorities = Array.isArray(value) ? value : [ value ];
		const hasPermission = userStore.hasAuthority(authorities);

		if (!hasPermission) {
			// 如果元素已存在但无权限,移除它
			if (el.parentNode) {
				el.remove();
			}
		} else {
			// 如果有权限但元素不存在,需要重新添加(这种情况较少见)
			// 这里不做处理,因为通常元素已经在 mounted 时被移除了
		}
	},
};