直接上代碼
src/mixins/lazyLoad.js
import { reactive } from 'vue'
export default function () {
const inView = reactive([])
const onIntersection = (entry) => {
if (entry.isIntersecting === true) {
add(`${entry.target.dataset.id}`)
}
}
function add(i) {
inView.push(i)
inView.sort(sortAtoi)
}
function sortAtoi(a, b) {
return Number(a) - Number(b)
}
return {
inView,
onIntersection
}
}
調用方法:
<template>
<card
v-for="(hotel, index) in hotelList"
:key="index"
v-intersection="onIntersection"
:in-view="inView.includes(`hotelCard-${index - 1}`)"
>
<!-- 代碼省略 -->
</card>
</template>
<script setup>
import LazyLoad from 'src/mixins/lazyLoad'
const { onIntersection, inView } = LazyLoad()
</script>
<style lang="scss" scoped>
/*--lazy load --*/
.in-view-item {
transition: all 0.3s;
display: block;
}
.in-view-enter,
.in-view-leave-to {
opacity: 0;
transform: translateX(-30px);
}
.in-view-leave-active {
position: absolute;
}
</style>
這裡的v-intersection是利用qusasr 套件的Directive
以上