生成一个vue3+ts轮播代码
时间: 2023-11-24 08:08:21 浏览: 91
好的,以下是一个简单的Vue3 TS轮播组件的代码示例:
```typescript
<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(${-currentIndex * 100}%)` }">
<div class="slide" v-for="(item, index) in items" :key="index">
<img :src="item.imgUrl" alt="">
</div>
</div>
<button class="arrow left" @click="prev">←</button>
<button class="arrow right" @click="next">→</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
interface SlideItem {
imgUrl: string
}
export default defineComponent({
name: 'Carousel',
props: {
items: {
type: Array as () => SlideItem[],
required: true
}
},
setup(props) {
const currentIndex = ref(0)
function prev() {
if (currentIndex.value === 0) {
currentIndex.value = props.items.length - 1
} else {
currentIndex.value--
}
}
function next() {
if (currentIndex.value === props.items.length - 1) {
currentIndex.value = 0
} else {
currentIndex.value++
}
}
return {
currentIndex,
prev,
next
}
}
})
</script>
<style scoped>
.carousel {
width: 100%;
position: relative;
overflow: hidden;
.slides {
display: flex;
transition: transform 0.5s;
.slide {
width: 100%;
img {
width: 100%;
}
}
}
.arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: none;
background: none;
color: #fff;
font-size: 2rem;
cursor: pointer;
&:focus {
outline: none;
}
&.left {
left: 10px;
}
&.right {
right: 10px;
}
}
}
</style>
```
当然,这只是一个简单的例子,你可以根据实际需求进一步扩展和优化这个轮播组件。
阅读全文