vue3+element-plus实现图片的轮转写一个组件代码和注释
以下是基于Vue3和Element-Plus实现图片轮播的组件代码和注释:
<template>
<div class="image-carousel">
<!-- 左箭头 -->
<el-button class="arrow arrow-left" icon="el-icon-arrow-left" @click="prev"></el-button>
<!-- 图片列表 -->
<div class="image-list">
<img v-for="(item, index) in images" :src="item" :key="index" :class="{active: currentIndex === index}">
</div>
<!-- 右箭头 -->
<el-button class="arrow arrow-right" icon="el-icon-arrow-right" @click="next"></el-button>
</div>
</template>
<script>
import { defineComponent, reactive } from 'vue';
export default defineComponent({
name: 'ImageCarousel',
props: {
images: {
type: Array,
required: true
}
},
setup(props) {
// 响应式数据,用于保存当前显示图片的索引
const state = reactive({
currentIndex: 0
});
// 切换到上一张图片
const prev = () => {
state.currentIndex = (state.currentIndex - 1 + props.images.length) % props.images.length;
};
// 切换到下一张图片
const next = () => {
state.currentIndex = (state.currentIndex + 1) % props.images.length;
};
return {
state,
prev,
next
};
}
});
</script>
<style scoped>
.image-carousel {
position: relative;
width: 100%;
height: 300px;
}
.arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.arrow-left {
left: 0;
}
.arrow-right {
right: 0;
}
.image-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.image-list img {
max-width: 100%;
max-height: 100%;
opacity: 0;
transition: opacity 0.5s;
}
.image-list img.active {
opacity: 1;
}
</style>
注释:
- 在模板中,使用Element-Plus的Button组件和img标签展示图片列表和箭头图标。
- 在setup函数中,使用reactive函数创建响应式数据state,以及prev和next两个方法。
- prev和next方法分别用于切换到上一张和下一张图片,通过计算currentIndex的值实现。
- 在样式中,设置组件的大小和箭头的位置,以及图片列表和图片的样式。使用opacity属性和transition属性实现图片的渐变切换效果
原文地址: https://www.cveoy.top/t/topic/dRpe 著作权归作者所有。请勿转载和采集!