效果圖
思路
給定一個變量用來記錄滾動了幾列,每滾動一次加1滾動一列,監聽頁面滾動父級元素寬度改變,重新設置滾動的距離(放在計算屬性中讓其自動計算)
<template>
<div class="container">
<el-button @click="prev">左滑</el-button>
<div class="box" ref="box">
<div
class="wrap"
ref="wrap"
:style="{ transform: `translateX(-${scrollX}px)` }"
>
<div
v-for="(item, index) in 8"
:key="index"
:style="{ width: widthItem + 'px' }"
:class="['item', 'item' + index]"
>
滾動{{ index }}
</div>
</div>
</div>
<el-button @click="next">右滑</el-button>
</div>
</template>
<script>
// 引入 npm install element-resize-detector --save
let elementResizeDetectorMaker = require("element-resize-detector");
export default {
props: {
// 顯示幾列
column: {
type: Number,
default: 5
}
},
data() {
return {
// 滾動了幾列
roll: 0,
// 每一列的寬度
widthItem: 0,
// 盒子總寬度
widthBox: 0
};
},
computed: {
scrollX() {
// flex布局時計算寬度,某些情況下會出現小數點,對比寬度比總寬度小1,使右滑出問題
return Math.ceil(this.roll * this.widthItem);
}
},
mounted() {
let erd = elementResizeDetectorMaker();
let _this = this;
// 監聽box元素寬度改變
erd.listenTo(this.$refs.box, function(element) {
_this.widthBox = element.offsetWidth;
// 計算每一列占多少行
_this.widthItem = element.offsetWidth / _this.column;
});
},
methods: {
next() {
let widthWrap = this.$refs.wrap.offsetWidth;
if (this.widthBox + this.scrollX >= widthWrap) return;
this.roll += 1;
},
prev() {
if (this.scrollX <= 0) return;
this.roll -= 1;
}
}
};
</script>
<style scoped lang="scss">
.container {
display: flex;
width: 100%;
height: 60px;
.box {
flex: 1;
border: 1px solid skyblue;
overflow: hidden;
.wrap {
display: inline-block;
white-space: nowrap;
transition: transform 0.3s;
.item {
display: inline-block;
height: 100%;
line-height: 60px;
text-align: center;
background-color: aquamarine;
}
}
}
}
</style>