vue实现初始化自动选中某个数据并滚动到某一位置
适用场景:多个商品根据传参选中某个商品,并将滚动条滚动到指定位置
<template>
<div>
<div
class="arr"
ref="scroll"
>
<div
class="img"
v-for="(item,index) in arr"
:key="index"
:class="[current==index?'active':''] "
@click="current=index"
>
<img
src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202103%2F09%2F20210309094501_jfyix.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1675911945&t=14dcf3ffd9b9884f4accc0941ed6f140"
alt=""
>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
arr: [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 9 },
{ id: 10 },
{ id: 11 },
],
current: 0,
listWidth: [],
};
},
mounted() {
this.$nextTick(() => {
this.current = 4;
this.getBoxHeight();
this.changeModel(4);
});
},
methods: {
getBoxHeight() {
// setTimeout(() => {
//延时计算元素的宽度
let rightItems = this.$refs.scroll.getElementsByClassName("img"); //获取指定类名的所有元素
let width = 0;
for (let i = 0; i < rightItems.length; i++) {
let item = rightItems[i]; // 右边的每一个模块(蓝色标题 + 标题下面所带的内容)
width += item.clientWidth;
this.listWidth.push(width); // 把右边模块内容的高度全都放到一个数组中
}
this.arr.forEach((item, index) => {
// 把上面弄的那些高度分别放入总数据中,方便点击左边让右边滚动到所对应的模块
this.$set(item, "distance", this.listWidth[index]);
});
// }, 1000); //增加延时,等图片渲染完毕后进行计算
},
changeModel(index) {
if (index == 0) {
this.$refs.scroll.scrollLeft = 0;
} else {
this.$refs.scroll.scrollLeft = this.arr[this.current].distance;
}
},
},
};
</script>
<style lang='scss' scoped>
.arr {
display: flex;
overflow-x: auto;
.img {
img {
width: 2rem;
height: 2rem;
object-fit: cover;
border-radius: 50%;
}
margin: 0 0.5rem 0 0;
}
.active {
img {
border: 0.1rem solid salmon;
}
}
}
</style>