vue自定义指令-常用指令案列

命名必须以v开头 简写模式在updated mounted钩子中执行

在这里插入图片描述

<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值