vue3+ts首页轮播图
时间: 2023-08-03 19:27:45 浏览: 127
首页轮播图
好的,以下是一个基于Vue3和TypeScript的首页轮播图的示例代码:
```html
<template>
<div class="slider">
<div class="slider__container" :style="{ transform: `translateX(${translateValue}px)` }">
<div class="slider__item" v-for="(item, index) in items" :key="index">
<img :src="item.imageSrc" alt="">
</div>
</div>
<div class="slider__controls">
<button class="slider__control" @click="prev">
<i class="fa fa-chevron-left"></i>
</button>
<button class="slider__control" @click="next">
<i class="fa fa-chevron-right"></i>
</button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
interface SliderItem {
imageSrc: string;
}
export default defineComponent({
name: 'Slider',
props: {
items: {
type: Array as () => SliderItem[],
required: true,
},
slideWidth: {
type: Number,
default: 1000,
},
},
setup(props) {
const currentIndex = ref(0);
const translateValue = computed(() => -currentIndex.value * props.slideWidth);
const prev = () => {
if (currentIndex.value === 0) {
currentIndex.value = props.items.length - 1;
} else {
currentIndex.value--;
}
};
const next = () => {
if (currentIndex.value === props.items.length - 1) {
currentIndex.value = 0;
} else {
currentIndex.value++;
}
};
return {
currentIndex,
translateValue,
prev,
next,
};
},
});
</script>
<style scoped>
.slider {
width: 100%;
height: 400px;
position: relative;
overflow: hidden;
}
.slider__container {
display: flex;
}
.slider__item {
width: 100%;
}
.slider__item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.slider__controls {
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
display: flex;
justify-content: space-between;
align-items: center;
}
.slider__control {
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
border: none;
padding: 10px;
cursor: pointer;
}
.slider__control i {
font-size: 24px;
}
</style>
```
在这个示例中,我们使用了Vue3的Composition API来定义组件。该组件接收一个`items`数组作为轮播图的数据源,并且还可以通过`slideWidth`属性来设置每张图片的宽度。在`setup`函数中,我们使用了`ref`函数来定义了一个`currentIndex`变量来标记当前显示的图片的索引,使用了`computed`函数来计算出图片容器的`transform`属性的值,从而实现图片滚动的效果。最后,我们定义了两个方法`prev`和`next`用于切换图片,并且将它们作为返回值暴露给模板使用。
该示例中还使用了一些CSS样式来实现轮播图的布局和样式。你可以根据自己的需求来修改样式。
阅读全文