安装 vueuse 插件
npm i @vueuse/core
搜索 useIntersectionObserver 方法
javascript
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
)
return {
target,
targetIsVisible,
}
},
}
使用:
main.js:
1、引入方法
javascript
// 用来图片懒加载
import { useIntersectionObserver } from "@vueuse/core";
2、提前配置好 自定义指令
javascript
// 全局指令
app.directive("img-lazy", {
mounted(el, binding) {
console.log(el, binding.value);
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }], observerElement) => {
console.log(isIntersecting);
if (isIntersecting) {
el.src = binding.value;
stop() //避免性能浪费,视口可见后不再监听
}
}
);
},
});
html部分:
javascript
<li v-for="item in list" :key="item.id">
<RouterLink to="/">
<img alt="" v-img-lazy="item.picture" />
<p class="name">{{ item.name }}</p>
<p class="price">¥{{ item.price }}</p>
</RouterLink>
</li>