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

vue3 自定义指令并实现页面元素平滑上升

基本示例

// 在directives/example.ts中
import type { Directive } from "vue";
/*** 示例*/
const example: Directive = {mounted(el) {console.log("mounted", el);},beforeUnmount(el) {console.log("beforeUnmount", el);}
};
export default example;

封装全局指令

// 在directives/index.ts中
import type { App, Directive } from "vue";
import example from "./example"; // 示例
const list: {[key: string]: Directive;
} = {example
};
const setDirectives = {install(app: App<Element>) {Object.keys(list).forEach((key) => {app.directive(key, list[key]);});}
};
export default setDirectives;

挂载

// 在main.ts中
import useDirective from "@/directives/index.ts"; // 自定义指令
const app = createApp(App);
app.use(useDirective);

使用

<div v-example></div>

元素平滑上升

import type { Directive } from "vue";
/*** 平滑滚动*/
const DISTANCE = 100;
const DURATION = 500;
const map = new WeakMap();
// 判断元素是否与视口区域重叠
const ob = new IntersectionObserver((entries) => {for (const entrie of entries) {// 出现在了视口if (entrie.isIntersecting) {const animation = map.get(entrie.target);animation && animation.play(); // 启动动画ob.unobserve(entrie.target); // 执行过之后就关闭监听}}
});
// 判断元素是否在视口区域
const isBelowViewport = (el: Element) => {const rect = el.getBoundingClientRect();return rect.top - window.innerHeight > 0;
};
const smoothScrolling: Directive = {mounted(el: Element) {// 已经在视口区域就不做处理if (!isBelowViewport(el)) return;// 动画配置const animation = el.animate([{transform: `translateY(${DISTANCE}px)`,opacity: "0.5"},{transform: `translateY(0)`,opacity: "1"}],{duration: DURATION,easing: "ease-out",fill: "forwards"});animation.pause(); // 暂停动画map.set(el, animation);ob.observe(el); // 监听元素是否进入视口},unmounted(el: Element) {ob.unobserve(el); // 关闭监听}
};
export default smoothScrolling;
http://www.zskr.cn/news/5058.html

相关文章:

  • abp记录
  • 重生之从零开始的神经网络算法学习之路 —— 第七篇 重拾 PyTorch(超分辨率重建和脚本的使用)
  • 从基础到实践(四十五):车载显示屏LCD、OLED、Mini-LED、MicroLED的工作原理、设计差异等说明 - 教程
  • 国产项目管理工具崛起:Gitee如何以本土化优势重构开发协作生态
  • GAS_Aura-Sending Gameplay Events
  • 进程间通信(消息队列)
  • 有点长所以单发的闲话(对acgn的看法(存疑))
  • Gitee:本土化创新赋能企业数字化转型,打造高效研发新范式
  • 修改Windows 资源器中文件的创建时间或更新时间
  • Mysql练习,15个必练语句带你玩转数据库
  • ios电脑如何改成windows系统
  • 内存一致性模型
  • Prometheus Probe 监控配置文档
  • 客户案例|邦普循环x甄知科技,筑牢高效智能的IT运维底座
  • 删边最短路
  • 一站式接入全球股票数据:日本、美国、印度、马来西亚等多国API对接实战
  • 基于MATLAB的图像处理程序
  • 跨网文件安全交换系统推荐厂商详解
  • SIM笔记
  • FTP替代工具哪个产品好,高效安全之选
  • c++之内存对齐模板类aligned_storage
  • 什么是网络分区
  • 完整教程:《驾驭云原生复杂性:隐性Bug的全链路防御体系构建》
  • 从机器的角度来说ECS为何性能好
  • 网络流笔记
  • 实用指南:经典动态规划题解
  • 2025杭电多校(2)
  • pyinstaller打包整个文件文件夹和相关exe,三方库
  • Web前端入门第 87 问:JavaScript 中 setInterval 和 setTimeout 细节
  • 虚拟电厂运行机制