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 type { Directive, DirectiveBinding } from "vue";
localStorage.setItem("userId", "wangzhy");
type Binding = string;
// mock 后台数据
const permission = ["wangzhy:shop:create", "wangzhy:shop:edit", "wangzhy:shop:delete"];
const userId = localStorage.getItem("userId") as string;
const vHasShow: Directive<HTMLElement, string> = (el, binding: DirectiveBinding<Binding>) => {
console.log(el, binding);
if (!permission.includes(userId + ":" + binding.value)) {
el.style.display = "none";
}
};
</script>
<style scoped>
button {
margin: 10px;
}
</style>
拖拽
<template>
<div v-move class="box">
<div class="header"></div>
<div>内容</div>
</div>
</template>
<script setup lang="ts">
import type { Directive, DirectiveBinding } from "vue";
const vMove: Directive<any, void> = (el: HTMLElement, binding: DirectiveBinding) => {
const moveEl: HTMLElement = el.firstElementChild as HTMLElement;
console.log(moveEl);
const mouseDown = (e: MouseEvent) => {
const x = e.clientX - el.offsetLeft;
const 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);
});
};
moveEl.addEventListener("mousedown", mouseDown);
};
</script>
<style scoped>
.box {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border: 3px solid black;
.header {
height: 20px;
background: black;
}
}
</style>
图片懒加载
核心是 IntersectionObserver 类的使用
<template>
<div>
<img v-lazy="item" width="360" height="360" :key="index" v-for="(item, index) in arr" alt="" />
</div>
</template>
<script setup lang="ts">
import type { Directive } from "vue";
const imageList: Record<string, { default: string }> = import.meta.glob("../assets/images/*.*", {
eager: true,
});
const arr = Object.values(imageList).map((v) => v.default);
console.log(arr);
console.log(imageList);
const vLazy: Directive<HTMLImageElement, string> = async (el, binding) => {
const def = await import("../assets/images/favicon.ico");
el.src = def.default;
const observer = new IntersectionObserver((enr) => {
console.log(enr[0], binding.value);
if (enr[0]?.intersectionRatio ?? 0 > 0) {
el.src = binding.value;
observer.unobserve(el);
}
});
observer.observe(el);
console.log(el);
};
</script>
<style scoped></style>