一、组件创建
首先,我们需要创建一个新的Vue组件,命名为HorizontalScrollGallery.vue
。
<template>
<div class="horizontal-scroll-gallery">
<div class="scroll-container">
<div
class="scroll-item"
v-for="(image, index) in images"
:key="index"
:style="{ backgroundImage: 'url(' + image.url + ')' }"
></div>
</div>
<button @click="scrollLeft">Previous</button>
<button @click="scrollRight">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
scrollWidth: 0,
itemWidth: 0,
items: [],
images: [
{ url: 'path/to/image1.jpg' },
{ url: 'path/to/image2.jpg' },
{ url: 'path/to/image3.jpg' },
// 更多图片
],
};
},
mounted() {
this.calculateDimensions();
window.addEventListener('resize', this.calculateDimensions);
},
beforeDestroy() {
window.removeEventListener('resize', this.calculateDimensions);
},
methods: {
calculateDimensions() {
this.scrollWidth = this.$el.clientWidth;
this.itemWidth = this.$el.querySelector('.scroll-item').clientWidth;
this.items = this.images.map(() => this.itemWidth);
},
scrollLeft() {
if (this.currentIndex > 0) {
this.currentIndex--;
}
},
scrollRight() {
if (this.currentIndex < this.images.length - 1) {
this.currentIndex++;
}
},
},
};
</script>
<style>
.horizontal-scroll-gallery {
overflow: hidden;
position: relative;
}
.scroll-container {
display: flex;
transition: transform 0.3s ease-in-out;
}
.scroll-item {
width: 100%; /* 根据实际情况调整 */
height: 300px; /* 根据实际情况调整 */
background-size: cover;
background-position: center;
}
</style>
二、样式设计
三、功能实现
在data
函数中,我们定义了以下属性:
currentIndex
:当前图片的索引。scrollWidth
:滚动容器的宽度。itemWidth
:单个图片项的宽度。items
:一个包含所有图片项宽度的数组。images
:包含图片URL的对象数组。