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