命名必须以v开头 简写模式在updated mounted钩子中执行
![在这里插入图片描述](https://img-blog.csdnimg.cn/11fdb807ed5d4b82b72a81fb4b537991.png)
<template>
<div class="directives-component" >
<input type="text" v-model="bgColor">
<div class="directives-box" v-bgcololr="{background:bgColor }" v-move></div>
<button class="btn" v-debounce="debounceClick">防抖</button>
<button class="btn" v-Permission="'b'">权限指令</button>
</div>
</template>
<script setup lang="ts">
import { ref, Directive, DirectiveBinding} from 'vue'
const bgColor = ref<string>('请输入背景色')
const vBgcololr = (el: HTMLElement, biding: DirectiveBinding) => {
el.style.background = biding.value.background
}
const vDebounce: Directive = (el:HTMLElement, biding: DirectiveBinding) => {
let timer: NodeJS.Timeout
el.addEventListener('click', () => {
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
biding.value()
}, 6000)
})
}
const debounceClick = () => {
console.log('只会触发一次')
}
const checkPermission = (value: string) => {
let hasPermission = ['a', 'c', 'd']
let index = hasPermission.indexOf(value)
if(index > -1){
return true
}
return false
}
const vPermission: Directive = (el: HTMLHtmlElement, binding: DirectiveBinding) => {
let hasPermission = checkPermission(binding.value)
if(!hasPermission){
el.parentNode && el.parentNode.removeChild(el)
}
}
const vMove: Directive = (el: HTMLElement, binding: DirectiveBinding) => {
const element = el as HTMLDivElement
const mousedown = (e: MouseEvent) => {
console.log('e', e)
const offsetX = e.clientX - el.offsetLeft
const offsetY = e.clientY - el.offsetTop
const move = (e: MouseEvent) => {
el.style.left = e.clientX - offsetX + 'px'
el.style.top = e.clientY - offsetY + 'px'
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', move)
})
}
element.addEventListener('mousedown', mousedown)
}
</script>
<style scoped lang="less">
.directives-component{
padding: 10px;
position: relative;
input{
width: 300px;
border: 2px solid #ccc;
}
.directives-box{
width: 300px;
height: 500px;
border: 2px solid #ccc;
border-top: 30px solid black;
position: absolute;
}
.btn{
width: 300px;
background-color: skyblue;
}
}
</style>