vue点击上下按钮图片切换轮播
时间: 2023-05-24 22:00:48 浏览: 284
可以使用v-bind来绑定图片的src属性,再利用v-on监听上下按钮的点击事件,并修改绑定的src属性值,达到图片切换的效果。
具体代码如下:
<template>
<div>
<img :src="imgUrl" alt="轮播图" height="400">
<button @click="prevImg">上一张</button>
<button @click="nextImg">下一张</button>
</div>
</template>
<script>
export default {
data() {
return {
imgs: [
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/id/238/200/300',
'https://picsum.photos/id/239/200/300',
'https://picsum.photos/id/240/200/300'
],
currentImgIndex: 0
}
},
methods: {
prevImg() {
this.currentImgIndex--;
if (this.currentImgIndex < 0) {
this.currentImgIndex = this.imgs.length - 1;
}
},
nextImg() {
this.currentImgIndex++;
if (this.currentImgIndex >= this.imgs.length) {
this.currentImgIndex = 0;
}
}
},
computed: {
imgUrl() {
return this.imgs[this.currentImgIndex];
}
}
}
</script>
阅读全文