feat(图片背景组件): 新增rootMargin和show参数,用于防止组件切换但是监控器失效

This commit is contained in:
hzj 2026-03-11 19:33:41 +08:00
parent 04b5441fb1
commit f60b0eec6a

View File

@ -17,7 +17,7 @@
:style="{ :style="{
width: '100%', width: '100%',
height: '100%', height: '100%',
backgroundColor: '#f0f0f0', backgroundColor: 'parent',
}" }"
></div> ></div>
@ -39,7 +39,7 @@
</template> </template>
<script setup> <script setup>
import { ref, onMounted, computed } from 'vue' import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
const props = defineProps({ const props = defineProps({
imgUrl: { imgUrl: {
@ -53,14 +53,20 @@ const props = defineProps({
default: '', default: '',
}, },
// //
lazy: { rootMargin: {
type: String,
default: '100px',
},
//
flip: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
// //
flip: { lazy: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
@ -70,10 +76,17 @@ const props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
//
show: {
type: Boolean,
default: true,
},
}) })
const containerRef = ref(null) const containerRef = ref(null)
const isVisible = ref(false) const isVisible = ref(false)
let observer = null
// //
const shouldShowImage = computed(() => { const shouldShowImage = computed(() => {
@ -100,7 +113,12 @@ const createObserver = () => {
if (!containerRef.value) return if (!containerRef.value) return
const observer = new IntersectionObserver( //
if (observer) {
observer.disconnect()
}
observer = new IntersectionObserver(
(entries) => { (entries) => {
entries.forEach((entry) => { entries.forEach((entry) => {
if (entry.isIntersecting) { if (entry.isIntersecting) {
@ -110,7 +128,8 @@ const createObserver = () => {
}) })
}, },
{ {
rootMargin: '100px', // 100px rootMargin: props.rootMargin, // 100px
threshold: 0,
}, },
) )
@ -120,6 +139,25 @@ const createObserver = () => {
onMounted(() => { onMounted(() => {
createObserver() createObserver()
}) })
// show
watch(
() => props.show,
(newVal) => {
if (newVal && props.lazy && !props.immediate) {
// DOM
setTimeout(() => {
createObserver()
}, 100)
}
},
)
onUnmounted(() => {
if (observer) {
observer.disconnect()
}
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>