【Vue3】自定义指令

简介: 【Vue3】自定义指令

除了 Vue 内置的一系列指令 (比如 v-modelv-show) 之外,Vue 还允许你注册自定义的指令 (Custom Directives)。

1. 生命周期钩子函数

一个自定义指令由一个包含类似组件生命周期钩子的对象来定义。钩子函数会接收到指令所绑定元素作为其参数。

<script setup> 中,任何以 v 开头的驼峰式命名的变量都可以被用作一个自定义指令。

<!-- App.vue -->
<template>
  <div>
    <button>切换</button>
    <!-- 
      钩子函数里面都可以接受这些值
      myParam: 自定义参数;
      myModifier: 自定义修饰符 
    -->
    <A v-move:myParam.myModifier="{ background: 'pink' }"></A>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, Directive } from 'vue';
import A from './components/A.vue';
import B from './components/B.vue';
let flag = ref<boolean>(true)
const vMove: Directive = {
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted(...args: Array<any>) {
    console.log('mounted')
    console.log(args);
  },
  beforeUpdate() {
    console.log('beforeUpdate')
  },
  updated() {
    console.log('updated')
  },
  beforeUnmount() {
    console.log('beforeUnmount')
  },
  unmounted() {
    console.log('unmounted')
  }
}
</script>
<style scoped lang="less"></style>

  • 0:该 div 元素。
  • 1:传入的参数等。比如 arg 参数,modifiers 自定义修饰符,dir 目录,传入的 value 值,instance 组件实例。
  • 2:当前组件的虚拟 DOM
  • 3:上一个虚拟 DOM
<!-- App.vue -->
<template>
  <div>
    <button>切换</button>
    <!-- 
      钩子函数里面都可以接受这些值
      myParam: 自定义参数;
      myModifier: 自定义修饰符 
    -->
    <A v-move:myParam.myModifier="{ background: 'pink' }"></A>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, Directive, DirectiveBinding } from 'vue';
import A from './components/A.vue';
import B from './components/B.vue';
let flag = ref<boolean>(true)
type Dir = {
  background: string;
}
const vMove: Directive = {
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted(el: HTMLElement, dir: DirectiveBinding<Dir>) {
    console.log('mounted')
    console.log(el);
    console.log(dir);
    el.style.background = dir.value.background;
  },
  // 传入的数据发生变化(比如此时的background)时触发 beforeUpdate 和 updated
  beforeUpdate() {
    console.log('beforeUpdate')
  },
  updated() {
    console.log('updated')
  },
  beforeUnmount() {
    console.log('beforeUnmount')
  },
  unmounted() {
    console.log('unmounted')
  }
}
</script>
<style scoped lang="less"></style>

2. 指令简写

<!-- App.vue -->
<template>
  <div class="btns">
    <button v-has-show="123">创建</button>
    <button>编辑</button>
    <button>删除</button>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, DirectiveBinding } from 'vue';
import type { Directive } from 'vue'
const vHasShow: Directive = (el, binding) => {
  console.log(el, binding) ;
}
</script>
<style scoped lang="less">
.btns {
  button {
    margin: 10px;
  }
}
</style>

应用场景1:按钮鉴权

根据能否从 localStorage(或者后台返回) 中获取数据,来判断是否显示某个按钮。

<!-- App.vue -->
<template>
  <div class="btns">
    <button v-has-show="'shop:create'">创建</button>
    <button v-has-show="'shop:edit'">编辑</button>
    <button v-has-show="'shop:delete'">删除</button>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, DirectiveBinding } from 'vue';
import type { Directive } from 'vue'
localStorage.setItem('userId', 'xiuxiu')
// mock 后台返回的数据
const permissions = [
  'xiuxiu:shop:create',
  // 'xiuxiu:shop:edit',  // 后台没有相应数据,则不显示该对应的按钮
  'xiuxiu:shop:delete'
]
const userId = localStorage.getItem('userId') as string
const vHasShow: Directive = (el, binding) => {
  if(!permissions.includes(userId + ':' + binding.value)) {
    el.style.display = 'none'
  }
}
</script>
<style scoped lang="less">
.btns {
  button {
    margin: 10px;
  }
}
</style>

应用场景2:鼠标拖拽

拖拽粉色框移动大盒子。

<!-- App.vue -->
<template>
  <div v-move class="box">
    <div class="header"></div>
    <div>内容</div>
  </div>
</template>
<script setup lang="ts">
import { Directive, DirectiveBinding } from 'vue';
const vMove:Directive<any,void> = (el:HTMLElement, binding:DirectiveBinding)=> {
  let moveElement:HTMLElement = el.firstElementChild as HTMLElement;
  console.log(moveElement);
  const mouseDown = (e:MouseEvent) => {
    // 记录原始位置
    // clientX 鼠标点击位置的X轴坐标
    // clientY 鼠标点击位置的Y轴坐标
    // offsetLeft 鼠标点击的子元素距离其父元素的左边的距离
    // offsetTop 鼠标点击的子元素距离其父元素的顶部的距离
    let X = e.clientX - el.offsetLeft;
    let Y = e.clientY - el.offsetTop;
    const move = (e:MouseEvent) => {
      console.log(e);
      el.style.left = e.clientX - X + 'px';
      el.style.top = e.clientY - Y + 'px';
    }
    document.addEventListener('mousemove', move);
    document.addEventListener('mouseup', () => {
      document.removeEventListener('mousemove', move);
    })
  }
  moveElement.addEventListener('mousedown', mouseDown);
}
</script>
<style scoped lang="less">
.box {
  position: fixed;
  height: 200px;
  width: 200px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #000;
  .header {
    height: 50px;
    width: 100%;
    background: pink;
    border-bottom: #000 1px solid;
  }
}
</style>

应用场景3:懒加载

let imageList = import.meta.glob('./assets/images/*.*', { eager: true })

let imageList = import.meta.glob('./assets/images/*.*')

// 判断图片是否在可视区
 const observer = new IntersectionObserver((e)=> {
   console.log(e[0]);
 })  
 // 监听元素
 observer.observe(el)

<!-- App.vue -->
<template>
  <div>
    <div>
      <img v-lazy="item" width="400" height="500" v-for="item in arr" alt="">
    </div>
  </div>
</template>
<script setup lang="ts">
import { Directive, DirectiveBinding } from 'vue';
let imageList:Record<string,{default:string}> = import.meta.glob('./assets/images/*.*', { eager: true })
let arr = Object.values(imageList).map(item=>item.default)
console.log(arr);
let vLazy:Directive<HTMLImageElement,string> = async (el,binding)=> {
  const def = await import('./assets/pinia.svg')
  el.src = def.default
  // 判断图片是否在可视区
  const observer = new IntersectionObserver((e)=> {
    console.log(e[0],binding.value);
    if(e[0].intersectionRatio > 0) {
      setTimeout(()=> {
        el.src = binding.value
      },2000)
      observer.unobserve(el)
    }
  })  
  // 监听元素
  observer.observe(el)
}
</script>
<style scoped lang="less"></style>
目录
相关文章
|
16天前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
162 12
|
5月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
755 5
|
2月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
282 1
|
2月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
151 0
|
3月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
100 0
|
5月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
435 17
|
6月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点
|
6月前
|
存储 JavaScript 前端开发
基于 ant-design-vue 和 Vue 3 封装的功能强大的表格组件
VTable 是一个基于 ant-design-vue 和 Vue 3 的多功能表格组件,支持列自定义、排序、本地化存储、行选择等功能。它继承了 Ant-Design-Vue Table 的所有特性并加以扩展,提供开箱即用的高性能体验。示例包括基础表格、可选择表格和自定义列渲染等。
425 6
|
5月前
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
1516 0
|
7月前
|
JavaScript 前端开发 UED
vue2和vue3的响应式原理有何不同?
大家好,我是V哥。本文详细对比了Vue 2与Vue 3的响应式原理:Vue 2基于`Object.defineProperty()`,适合小型项目但存在性能瓶颈;Vue 3采用`Proxy`,大幅优化初始化、更新性能及内存占用,更高效稳定。此外,我建议前端开发者关注鸿蒙趋势,2025年将是国产化替代关键期,推荐《鸿蒙 HarmonyOS 开发之路》卷1助你入行。老项目用Vue 2?不妨升级到Vue 3,提升用户体验!关注V哥爱编程,全栈开发轻松上手。
455 2

热门文章

最新文章