创建一个directives/hasPermission.ts
自定义用户权限事件:
export const hasPermission = {
created(el, bindings) {
const token = localStorage.getItem("token"); //用户登录态
el.addEventListener('click', () => {
if (!token) {
console.log('请先登录');
} else {
console.log('已登录');
bindings.value(); // 调用绑定的事件
}
})
}
}
通过directives/index.ts
import { hasPermission } from "./hasPermission";
const directive = { // 存放自定义指令集
hasPermission
}
export default function (app) {
// 批量注册自定义指令
Object.keys(directive).forEach(key => {
app.directive(key, directive[key])
})
}
在页面使用:
<template>
<div v-hasPermission="handlerClick">
</div>
</template>
<script lang="ts" setup>
const handlerClick = () => {
console.log("成功后,会执行我")
}
</script>
<style lang="scss">
</style>