当前位置: 首页 > news >正文

Vue3自定义指令(directive)

文章目录

  • 前言
  • 一、Vue3指令钩子函数
  • 二、自定义指令的两种方式
    • 1.局部使用
      • 例子1:鉴权
      • 例子2:拖拽
    • 2.全局使用
      • 例子1:监听宽高指令
      • 例子2:监听是否出现在视口
  • 总结


前言

此文章主要讲了vue3中自定义指令的使用,以及一些WebAPI的使用。如 ResizeObserver、IntersectionObserver API的使用。


一、Vue3指令钩子函数

  • created 元素初始化
  • beforeMount 指令绑定到元素后调用 只调用一次
  • mounted 元素插入父级dom调用
  • beforeUpdate 元素被更新前调用
  • updated 元素被更新后调用
  • beforeUnmount 元素移除前调用
  • unmounted 元素被移除后调用

vue2中的指令钩子函数有:

bind、inserted、update、componentUpdated、unbind

二、自定义指令的两种方式

利用Directive可以创建自定义指令

1.局部使用

接收两个参数
el:表示当前组件实例
dir:表示传入的参数以及函数

DirectiveBinding:与返回参数一致,使用来约束类型

export interface DirectiveBinding<V = any> {instance: ComponentPublicInstance | null;value: V;oldValue: V | null;arg?: string;modifiers: DirectiveModifiers;dir: ObjectDirective<any, V>;
}

使用如下:

<script setup lang="ts">
import {Directive, DirectiveBinding} from "vue";
import A from "./A.vue";
type Dir = {background:string
}
const vMove:Directive = {created(){console.log('------created-------')},beforeMount(){console.log('------beforeMount-------')},mounted(el:HTMLElement,dir:DirectiveBinding<Dir>){console.log('------mounted-------')el.style.background = dir.value.background},beforeUpdate(){console.log('------beforeUpdate-------')},updated(){console.log('------updated-------')},beforeUnmount(){console.log('------beforeUnmount-------')},unmounted(){console.log('------unmounted-------')}
}
</script><template>
<A v-move:aaa.smz="{background:'red'}"/>
</template>

例子1:鉴权

<script setup lang="ts">
import {Directive} from "vue";// 用户id
localStorage.setItem('userId','smz')
// mock后台数据
const permission = ['smz:shop:edit',// 'smz:shop:create','smz: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><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>

例子2:拖拽

这里使用拖拽需要改变拖拽的position,因为不改变,则修改元素位置不起作用

static
该关键字指定元素使用正常的布局行为,即元素在文档常规流中当前的布局位置。此时 top, right, bottom, left 和 z-index 属性无效。

<script setup lang="ts">
/*** Element.firstElementChild:只读属性,返回对象第一个子元素,没有则返回Null* Element.clientX:只读属性,元素距离视口左边的距离(中心点)* Element.offsetLeft:只读属性,元素左上角距离视口左边的距离* Element.offsetWidth:元素宽度* Element.offsetHeight:元素高度* window.innerWidth:可视窗宽度* window.innerHeight:可视窗高度*/
import {Directive, DirectiveBinding} from "vue";const vDrea:Directive<any,void> = (el:HTMLElement,binding:DirectiveBinding)=>{let gap = 10let moveElement:HTMLDivElement = el.firstElementChild as HTMLDivElementconst mouseDown = (e:MouseEvent)=>{console.log(window.innerHeight)let X = e.clientX - el.offsetLeftlet Y = e.clientY - el.offsetTopconst move = (e:MouseEvent)=>{let x = e.clientX - Xlet y = e.clientY - Y//超出边界判断if (x<=gap){x = 0}if (y<=gap){y = 0}if (x>= window.innerWidth -el.offsetWidth -gap){x = window.innerWidth -el.offsetWidth}if (y>= window.innerHeight - el.offsetHeight-gap){y = window.innerHeight - el.offsetHeight}el.style.left = x + 'px'el.style.top = y + 'px'}// 鼠标移动document.addEventListener('mousemove',move)//松开鼠标document.addEventListener('mouseup',()=>{//清除移动事件document.removeEventListener('mousemove',move)})}//鼠标按下moveElement.addEventListener('mousedown',mouseDown)
}
</script><template><div v-drea class="box"><div class="header"></div><div>内容</div></div>
</template><style lang="less" scoped>
.box{position: fixed;width: 300px;height: 250px;border: solid 1px black;.header{height: 30px;background-color: black;}
}
</style>

2.全局使用

定义好全局指令文件,其中需要导出指令钩子函数

/*** el:监听的dom元素* binding: 回调事件*/
export default {mounted(el,binding) {//将dom与回调的关系塞入mapmap.set(el,binding.value)//监听el元素的变化ob.observe(el)},unmounted(el) {//取消监听ob.unobserve(el)}
}

在main.ts文件中添加以下代码
挂载指令,省略‘v-’前缀

import sizeDireect from '../src/directs/resize指令封装/sizeDireect'
app.directive('size-ob', sizeDireect)

使用:
在需要监听的标签上使用命令 v-size-ob="handle",其中handle为回调函数,其中返回的参数为尺寸信息

 <div class="dir"  v-size-ob="handle">

例子1:监听宽高指令

/*** @ResizeObserver 监听元素变化的API* @entries 元素变化的数组集合* @entry 每个被监听的元素 其中包含的属性有:*    borderBoxSize:边框盒尺寸*    contentBoxSize:内容盒尺寸*    contentRect:内容区域矩形信息 => DOMRectReadOnly {x: 0, y: 0, width: 3800, height: 3800, top: 0, …}*    devicePixelContentBoxSize:DPR尺寸*    target:哪一个元素发生变化*/
const ob = new ResizeObserver((entries)=>{for (const entry of entries) {// 获取dom元素的回调const handler = map.get(entry.target)//存在回调函数if (handler){// 将监听的值给回调函数handler({width: entry.borderBoxSize[0].inlineSize,height: entry.borderBoxSize[0].blockSize})}}
})
/*** map:存储dom与回调函数的映射关系* 使用WeakMap,防止内存溢出*/
const map = new WeakMap();
/*** el:监听的dom元素* binding: 回调事件*/
export default {mounted(el,binding) {//将dom与回调的关系塞入mapmap.set(el,binding.value)//监听el元素的变化ob.observe(el)},unmounted(el) {//取消监听ob.unobserve(el)}
}

例子2:监听是否出现在视口

vite提供了批量导入的方法 import.meta.glob
eager:true表示静态导入

let imageList: Record<string,{default: string}> = import.meta.glob('../../../assets/images/*.*',{eager:true})
let arr = Object.values(imageList).map(v=>v.default)
/*** IntersectionObserver:监听元素与视口交叉的API* 返回一个监听集合,集合每一项有intersectionRatio表示在视口存在的比例*/
export default {// @ts-ignoreasync mounted(el,binding){const def = await import('../../assets/vue.svg')el.src = def.defaultlet ob = new IntersectionObserver((entries) => {if (entries[0].intersectionRatio >0){el.src = binding.valueOf()ob.unobserve(el)}})ob.observe(el)},unmounted(el){}
}

总结

此文章主要讲了vue3中自定义指令的使用,以及一些WebAPI的使用。如 ResizeObserver、IntersectionObserver API的使用

http://www.lryc.cn/news/165032.html

相关文章:

  • 大数据课程L9——网站流量项目的实时业务处理代码
  • 【2023最新B站评论爬虫】用python爬取上千条哔哩哔哩评论
  • mysql设置max_sp_recursion_depth,sql_mode
  • 论文阅读:SERE: Exploring Feature Self-relation for Self-supervised Transformer
  • 遥感数据与作物模型同化应用:PROSAIL模型、DSSAT模型、参数敏感性分析、数据同化算法、模型耦合、精度验证等主要环节
  • Navicat15工具连接PostgreSQL15失败
  • 开源AI家庭自动化助手-手机控制家庭智能家居服务
  • 解决CSS定位错乱/疑难杂症的终极绝招==》从样式污染开始排查
  • 【笔记】《C++性能优化指南》Ch3 测量性能
  • 2023大数据面试总结
  • udev自动创建设备节点的机制
  • 访问局域网内共享文件时报错0x80070043,找不到网络名
  • Java定时器
  • 科普js加密时出现的错误
  • MYSQL优化——B+树讲解
  • Rokid Jungle--Station pro
  • 如何实现微服务
  • MySQL如何进行增量备份与恢复?
  • 微服务框架
  • (matplotlib)如何让各个子图ax大小(宽度和高度)相等
  • python http 上传文件
  • IPO解读:Instacart曲折上市,业务模式如何持续“绚烂”?
  • 使用sql profile 稳定执行计划的案例
  • 海南大学金秋悦读《乡村振兴战略下传统村落文化旅游设计》2023新学年许少辉八一新书​
  • [N0wayback 2023春节红包题] happyGame python反编译
  • Redis 初识与入门
  • 【STM32】片上ADC的初步使用
  • esxi下实现ikuai相同的两个网卡,单独路由配置
  • Windows环境下Elasticsearch相关软件安装
  • 配置Jedis连接池