2023-11-27 vue自定义平滑出现指令 新建指令文件 smooth.js1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950const DISTIANCE = 50;const DURATION = 1000;const animationMap = new WeakMap(); // 防止内存泄露const ob = new IntersectionObserver((entries) => { for (const entry of entries) { if (entry.isIntersecting) { const animation = animationMap.get(entry.target); animation.play(); ob.unobserve(entry.target); // 取消监听 } }});function isBelowViewport(el) { const rect = el.getBoundingClientRect(); return rect.top > window.innerHeight;}export default { mounted(el) { if (!isBelowViewport(el)) { return; } const animation = el.animate( [ { transform: `translateY(${DISTIANCE}px)`, opacity: 0.5, }, { transform: `transformY(0)`, opacity: 1, }, ], { duration: DURATION, easing: "ease", } ); animation.pause(); animationMap.set(el, animation); ob.observe(el); }, unmounted(el) { ob.unobserve(el); },}; 使用:在 main.js 中引入12import smoothDirective from "./directives/smooth";app.directive("wu-smooth", smoothDirective); 在需要平滑上移的元素中添加指令:1234<ul> <li v-wu-smooth>666</li> <li v-wu-smooth>6666</li></ul> 前一篇 使用 Immer 实现在 Zustand 中更新深层对象 后一篇 React学习笔记