Appearance
自定义指令directive
directive-自定义指令(属于破坏性更新)
vue中有v-if,v-for,v-bind,v-show,v-model 等等一系列方便快捷的指令 今天一起来了解一下vue里提供的自定义指令
Vue3指令的钩子函数
created元素初始化的时候beforeMount指令绑定到元素后调用 只调用一次mounted元素插入父级dom调用beforeUpdate元素被更新之前调用update这个周期方法被移除 改用updatedbeforeUnmount在元素被移除前调用unmounted指令被移除后调用 只调用一次 Vue2 指令 bind inserted update componentUpdated unbind
在setup内定义局部指令
但这里有一个需要注意的限制:必须以 vNameOfDirective 的形式来命名本地自定义指令,以使得它们可以直接在模板中使用。
html
<template>
<button @click="show = !show">开关{{show}} ----- {{title}}</button>
<Dialog v-move-directive="{background:'green',flag:show}"></Dialog>
</template>ts
type Value = {
background: string
}
const vMoveDirective: Directive = {
created: () => {
console.log("初始化====>");
},
beforeMount(...args: Array<any>) {
// 在元素上做些操作
console.log("初始化一次=======>");
},
// 添加泛型,可以方便dir.value.的时候出现提示
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("======>卸载完成");
},
};函数简写
你可能想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将这个函数模式实现
ts
type Dir = {
background: string
}
const vMove: Directive = (el, binding: DirectiveBinding<Dir>) => {
el.style.background = binding.value.background
}TIP
第一个 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 钩子中可用
自定义按钮权限指令
vue
<template>
<div>
<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 {Directive, DirectiveBinding} from "vue";
const userId = 'xiaomanzs'
const permission = [
'xiaomanzs:shop:create',
// 'xiaomanzs:shop:edit', 删除该数据后,编辑按钮在页面就隐藏了
'xiaomanzs:shop:delete'
]
const vHasShow: Directive<HTMLElement, string> = (el, bingding) => {
console.log(bingding)
// 不包含 就将按钮隐藏
if (!permission.includes(userId + ':' + bingding.value)) {
el.style.display = 'none'
}
}
</script>
<style scoped>
</style>自定义拖拽指令
vue
<template>
<div v-move class="box">
<div class="header"></div>
<div>内容</div>
</div>
</template>
<script setup lang="ts">
import {Directive} from "vue";
const vMove: Directive<any, void> = (el, binding) => {
let moveElement = el.firstElementChild as HTMLDivElement
console.log(moveElement)
// 定义按下的事件监听
const mouseDown = (e: MouseEvent) => {
console.log(e)
console.log(el.offsetLeft)
console.log(el.style)
// el的offsetLeft 是整体中心距离左边的距离
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>
.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>自定义指令实现图片懒加载
vue
<template>
<div>
<img v-lazy="item" width="360" height="300"
v-for="item in arr" :key="item" alt=""
>
</div>
</template>
<script setup lang="ts">
import {Directive} from "vue";
let imgList = import.meta.glob('./assets/*.*', {eager: true})
console.log(imgList)
// 使用glob,不添加 `eager:true` 的时候,的写法
// for (const path in imgList) {
// imgList[path]().then((mod)=>{
// console.log(path,mod)
// })
// }
let arr = Object.values(imgList).map(v => v.default)
let vLazy: Directive<HTMLImageElement, string> = async (el, binding) => {
const def = await import('./assets/vue.svg')
console.log('def', def)
el.src = def.default
// el.src = binding.value
//IntersectionObserver 判断是否在可视区内
const observer = new IntersectionObserver((entries) => {
console.log('----', entries[0], binding.value)
if (entries[0].intersectionRatio > 0) {
setTimeout(() => {
el.src = binding.value
}, 1000)
observer.unobserve(el)
}
})
observer.observe(el)
}
// console.log(arr)
// 给一个数组和一个和,计算数组包含能使相加等于和的两个数的下标
const twoSum = (nums: number[], target: number): number[] => {
let map = new Map()
for (let i = 0; i < nums.length; i++) {
const res = target - nums[i]
if (map.has(res)) {
return [map.get(res), i]
}
map.set(nums[i], i)
}
return []
};
let a = twoSum([2, 7, 11, 15], 9)
console.log(a)
</script>
<style scoped>
</style>