vue3+vite+ts 自定义指令详解

news/2024/9/22 22:31:40/
  1. directive-自定义指令(属于破坏性更新)

    Vue中有v-if,v-for,v-bind,v-show,v-model 等等一系列方便快捷的指令 今天一起来了解一下vue里提供的自定义指令

Vue3指令的钩子函数
created 元素初始化的时候
beforeMount 指令绑定到元素后调用 只调用一次
mounted 元素插入父级dom调用
beforeUpdate 元素被更新之前调用
update 这个周期方法被移除 改用updated
beforeUnmount 在元素被移除前调用
unmounted 指令被移除后调用 只调用一次
Vue2 指令 bind inserted update componentUpdated unbind

  1. 在setup内定义局部指令
    但这里有一个需要注意的限制:必须以 vNameOfDirective 的形式来命名本地自定义指令,以使得它们可以直接在模板中使用。
javascript"><template><button @click="show = !show">开关{{show}} ----- {{title}}</button><Dialog  v-move-directive="{background:'green',flag:show}"></Dialog>
</template>
javascript"> 
const vMoveDirective: Directive = {created: () => {console.log("初始化====>");},beforeMount(...args: Array<any>) {// 在元素上做些操作console.log("初始化一次=======>");},mounted(el: any, dir: DirectiveBinding<Value>) {el.style.background = dir.value.background;console.log("初始化========>");},beforeUpdate() {console.log("更新之前");},updated() {console.log("更新结束");},beforeUnmount(...args: Array<any>) {console.log(args);console.log("======>卸载之前");},unmounted(...args: Array<any>) {console.log(args);console.log("======>卸载完成");},
};

3.生命周期钩子参数详解

  • 第一个 el 当前绑定的DOM 元素

  • 第二个 binding

    instance:使用指令的组件实例。
    value:传递给指令的值。例如,在 v-my-directive=“1 + 1” 中,该值为 2。
    oldValue:先前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否有更改都可用。
    arg:传递给指令的参数(如果有的话)。例如在 v-my-directive:foo 中,arg 为 “foo”。
    modifiers:包含修饰符(如果有的话) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}。
    dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中

  • 第三个 当前元素的虚拟DOM 也就是Vnode

  • 第四个 prevNode 上一个虚拟节点,仅在 beforeUpdate 和 updated 钩子中可用

4.函数简写
你可能想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将这个函数模式实现

javascript"><template><div><input v-model="value" type="text" /><DVue v-move="{ background: value }"></DVue></div>
</template><script setup lang='ts'>
import DVue from './components/D.vue'
import { ref, Directive, DirectiveBinding } from 'vue'
let value = ref<string>('')
type Dir = {background: string
}
const vMove: Directive = (el, binding: DirectiveBinding<Dir>) => {el.style.background = binding.value.background
}
</script>

5.示例Demo
1.按钮权限按钮

javascript"><template><div style="margin-top: 20px"><el-button v-has-show="'shop:create'">创建</el-button><el-button v-has-show="'shop:edit'">编辑</el-button><el-button v-has-show="'shop:delete'">删除</el-button></div>
</template>
<script setup lang="ts">
import type { Directive } from "vue"
localStorage.setItem("userId", "myYYDS")
// mock后台返回的数据
const permission = ["myYYDS:shop:edit","myYYDS:shop:create","myYYDS:shop:delete",
]
const userId = localStorage.getItem("userId") as string
const vHasShow: Directive<HTMLElement, string> = (el, bingding) => {if (!permission.includes(userId + ":" + bingding.value)) {el.style.display = "none"}
}
</script>
<style scoped lang="scss"></style>
  1. 移动 自定义拖拽指令
    在这里插入图片描述
javascript"><template><div style="margin-top: 20px" v-move class="box"><div class="header"></div><div>我移动啦</div></div>
</template>
<script setup lang="ts">
import type { Directive } from "vue"
const vMove: Directive<any, void> = (el: HTMLElement) => {let moveElement: HTMLDivElement = el.firstElementChild as HTMLDivElementconst mouseDown = (e: MouseEvent) => {let X = e.clientX - el.offsetLeftlet Y = e.clientY - el.offsetTopconst move = (e: MouseEvent) => {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="scss">
.box {position: fixed;left: 50%;top: 50%;transform: translate(-50%, -50%);width: 200px;height: 200px;border: 1px solid #ccc;.header {height: 20px;background: black;cursor: move;}
}
</style>

3.图片懒加载

javascript"><template><div v-for="item in arr"><img height="500" :data-index="item" v-lazy="item" width="360" alt="" /></div>
</template>
<script setup lang="ts">
import { Directive } from "vue"// vite 提供的方法可以引入全部的图片
// glob:是懒加载的模式
// globEager 静态加载全部
let imageList: Record<string, { default: string }> = import.meta.glob("../../assets/images/*.*",{ eager: true },
)
let arr = Object.values(imageList).map((v) => v.default)let vLazy: Directive<HTMLImageElement, string> = async (el, bingding) => {const def = await import("../../assets/vue.svg")el.src = def.default// 判断元素是否是可视区域const observer = new IntersectionObserver((enr) => {if (enr[0].intersectionRatio) {setTimeout(() => {el.src = bingding.value}, 2000)}})observer.observe(el)
}
</script>
<style scoped lang="scss"></style>

在这里插入图片描述
在这里插入图片描述


http://www.ppmy.cn/news/1458833.html

相关文章

gtest的编译与使用

文章目录 gtest的编译与使用概述笔记CMake参数官方文档测试程序测试效果END gtest的编译与使用 概述 gTest是 googletest的缩写&#xff0c;如果直接找gTest项目&#xff0c;是找不到的。 库地址 https://github.com/google/googletest.git 迁出到本地后&#xff0c;切到最新…

AI智能分析高精度烟火算法EasyCVR视频方案助力打造森林防火建设

一、背景 随着夏季的来临&#xff0c;高温、干燥的天气条件使得火灾隐患显著增加&#xff0c;特别是对于广袤的森林地区来说&#xff0c;一旦发生火灾&#xff0c;后果将不堪设想。在这样的背景下&#xff0c;视频汇聚系统EasyCVR视频融合云平台AI智能分析在森林防火中发挥着至…

智慧公厕:打造智能、安全、舒适的公共厕所新时代

随着智慧城市建设的不断推进&#xff0c;公共设施的智能化也已成为一种必然趋势。在这一背景下&#xff0c;智慧公厕作为城市管理的一个重要方面&#xff0c;正逐渐走进人们的视野。通过对所在辖区内所有公共厕所的全域感知、全网协同、全业务融合以及全场景智慧的赋能&#xf…

Redis-2 双写一致性

双写一致性 一.什么是双写一致性&#xff1f; 在数据库中的数据修改后&#xff0c;也要修改缓存中的数据&#xff0c;保证数据库与缓存中保存的数据一致。 二.如何保证双写一致性&#xff1f; 回答该问题一定要结合自己的项目&#xff0c;说明自己的项目是必须强一致性还是…

面试中算法(使用栈实现队列)

使用栈来模拟一个队列&#xff0c;要求实现队列的两个基本操作:入队、出队。 栈的特点&#xff1a;先入后出&#xff0c;出入元素都是在同一端&#xff08;栈顶&#xff09;。 队列的特点&#xff1a;先入先出&#xff0c;出入元素是在两端&#xff08;队头和队尾)。 分析&…

hbase建表预分区的2种方法

以下案例建表并设置预分区,分别测试以下2种方法 1.固定散列 示例:rowkey以日期为前缀 create ‘test’,‘cf1’, SPLITS > [‘202401’, ‘202402’, ‘202403’] put ‘test’,‘20240101’,‘cf1:name’,‘20240101’ put ‘test’,‘20240102’,‘cf1:name’,‘2024010…

neo4j-5.11.0安装APOC插件or配置允许使用过程的权限

在已经安装好neo4j和jdk的情况下安装apoc组件&#xff0c;之前使用neo4j-community-4.4.30&#xff0c;可以找到配置apoc-4.4.0.22-all.jar&#xff0c;但是高版本neo4j对应没有apoc-X.X.X-all.jar。解决如下所示&#xff1a; 1.安装好JDK与neo4j 已经安装对应版本的JDK 17.0…

linux高性能服务器--Ngix内存池简单实现

文章目录 内存模型&#xff1a;流程图内存对齐code 内存模型&#xff1a; 流程图 内存对齐 对齐计算 要分配一个以指定大小对齐的内存&#xff0c;可以使用如下公式&#xff1a; 假设要分配大小为n&#xff0c;对齐方式为x&#xff0c;那么 size(n(x-1)) & (~(x-1))。 举个…