vue自定义平滑出现指令

新建指令文件 smooth.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const 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 中引入

1
2
import smoothDirective from "./directives/smooth";
app.directive("wu-smooth", smoothDirective);

在需要平滑上移的元素中添加指令:

1
2
3
4
<ul>
<li v-wu-smooth>666</li>
<li v-wu-smooth>6666</li>
</ul>