问题:监听元素的宽度变化(不一定是屏幕宽度才能导致元素变化,也肯能是其他元素的变化导致的)
// 指标控制 适用于 一些指标显示的地方 根据元素宽度 一行来显示不同的个数
<template>
<div id="aaa"></div>
</template>
export default {
data() {
return {
indexControlNum: 25,
timerWidth: null,
resizeObserver: null,
observedElement: null
}
},
mounted() {
this.doIndexControl(`aaa`)
},
beforeDestroy() {
// 在组件销毁前,取消对目标元素的观察
this.resizeObserver.unobserve(this.observedElement)
// 断开 ResizeObserver 实例与回调函数的连接,释放资源
this.resizeObserver.disconnect()
},
methods: {
doIndexControl(id) {
// / 创建 ResizeObserver 实例
this.resizeObserver = new ResizeObserver(entries => {
// 当观察到元素大小变化时触发的回调函数
for (let entry of entries) {
// 获取元素的宽度
const width = entry.contentRect.width
// 在这里可以根据需要进行处理,例如更新数据或触发其他操作
if (this.timerWidth) clearTimeout(this.timerWidth)
this.timerWidth = setTimeout(() => {
// 150宽度来算
if (width < 450) {
// 2个 300
this.indexControlNum = 50
} else if (width < 600) {
// 3个 450
this.indexControlNum = 33.3
} else if (width < 750) {
// 4个 600
this.indexControlNum = 25
} else if (width < 900) {
// 5个 750
this.indexControlNum = 20
} else if (width < 1050) {
// 6个
this.indexControlNum = 16.6
} else if (width < 1200) {
// 7个
this.indexControlNum = 14.2
} else if (width < 1350) {
// 8个
this.indexControlNum = 12.5
} else if (width < 1500) {
// 9个
this.indexControlNum = 11.1
} else if (width < 1650) {
// 10个
this.indexControlNum = 10
} else if (width < 1800) {
// 11个
this.indexControlNum = 9.09
} else if (width < 1950) {
// 12个
this.indexControlNum = 8.33
} else if (width < 2100) {
// 13个
this.indexControlNum = 7.69
} else if (width < 2250) {
// 14个
this.indexControlNum = 7.14
} else if (width < 2400) {
// 15个
this.indexControlNum = 6.66
} else if (width < 2550) {
// 16个
this.indexControlNum = 6.25
}
clearTimeout(this.timerWidth)
this.timerWidth = null
}, 300)
}
})
let timer = setTimeout(() => {
this.observedElement = document.getElementById(id)
this.resizeObserver.observe(this.observedElement)
clearTimeout(timer)
}, 500)
}
}
}