Vue瀑布流
data() {
return {
colCount: 0,
colHeightArry: [],
boxWidth: 0,
mainWidth: 0
}
},
watch: {
mainWidth: {
handler(val) {
this.colHeightArry = []
this.boxWidth = this.$refs.box[0].clientWidth
if (val === 1180) {
this.colCount = 3
} else {
this.colCount = 4
}
this.reset()
}
}
},
mounted() {
window.onresize = () => {
this.$nextTick(() => {
this.mainWidth = this.$refs.main.clientWidth
})
}
// 根据页面宽度不同显示不同的个数,如果在watch中加载读取不到this.$refs
this.mainWidth = this.$refs.main.clientWidth
this.boxWidth = this.$refs.box[0].clientWidth
if (this.mainWidth === 1180) {
this.colCount = 3
} else {
this.colCount = 4
}
this.reset()
},
methods: {
reset() {
const { colHeightArry, colCount, boxWidth } = this
this.$refs.box.forEach((item, index) => {
if (index < colCount) {
item.style.top = 0
item.style.left = `${boxWidth * index + index * 18}px`
colHeightArry.push(item.offsetHeight)
} else {
let minHeight = colHeightArry[0]
let minIndex = 0
colHeightArry.forEach((p, pindex) => {
if (minHeight > p) {
minHeight = p
minIndex = pindex
}
})
item.style.top = `${colHeightArry[minIndex] + 20}px`
item.style.left = `${boxWidth * minIndex + minIndex * 18}px`
colHeightArry[minIndex] =
colHeightArry[minIndex] + item.offsetHeight + 20
}
})
}
}