当前位置: 首页 > 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.wxhsa.cn/company.asp?id=4538

相关文章:

  • abp记录
  • 强化学习(二十):模仿学习
  • 重生之从零开始的神经网络算法学习之路 —— 第七篇 重拾 PyTorch(超分辨率重建和脚本的使用)
  • 从基础到实践(四十五):车载显示屏LCD、OLED、Mini-LED、MicroLED的工作原理、设计差异等说明 - 教程
  • 国产项目管理工具崛起:Gitee如何以本土化优势重构开发协作生态
  • GAS_Aura-Sending Gameplay Events
  • 【IEEE-智造领空天,寰宇链未来】第五届机电一体化技术与航空航天工程国际学术会议(ICMTAE 2025)
  • 进程间通信(消息队列)
  • 有点长所以单发的闲话(对acgn的看法(存疑))
  • 【光照】Unity中的[光照模型]概念辨析
  • 深入解析:Shell脚本监控系统资源详解
  • 计算几何全家桶
  • 完整教程:从无声视频中“听见”声音:用视觉语言模型推理音频描述
  • Win10如何安装语音包
  • C#通过TCP/IP控制康奈视读码枪实现方案
  • 链表
  • 利用三方APP[IP切换助手]使用socks5
  • 智能卫浴雷达模块感应方案WT4101寿命长不怕干扰
  • 修改Windows 资源器中文件的创建时间或更新时间
  • Mysql练习,15个必练语句带你玩转数据库
  • 威力导演2026中文版 CyberLink PowerDirector 2026 v24.0 旗舰版更新内容
  • 越权漏洞
  • GAS_Aura-Ability Tasks
  • 本地大模型的崛起:为什么越来越多人不用云端 AI?
  • Gitee:国产代码托管平台如何重塑企业研发效能版图
  • CompassBench 大模型评测
  • Windows截图工具Acropalypse漏洞剖析:开发者中心安全的重要教训
  • bootstrap-flex总结
  • 【源码解读之 Mybatis】【基础篇】-- 第2篇:配置系统深度解析
  • eSIM笔记