feat(图片背景组件): 新增rootMargin和show参数,用于防止组件切换但是监控器失效
This commit is contained in:
parent
04b5441fb1
commit
f60b0eec6a
@ -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>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user