vue 实现图片切换
Vue 实现图片切换的方法
基础图片切换(数组遍历)
通过v-for遍历图片数组,结合v-bind动态绑定图片路径:
<template>
<div>
<img :src="currentImage" alt="Current Image">
<button @click="prevImage">上一张</button>
<button @click="nextImage">下一张</button>
</div>
</template>
<script>
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
currentIndex: 0
}
},
computed: {
currentImage() {
return this.images[this.currentIndex]
}
},
methods: {
nextImage() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
},
prevImage() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
}
}
}
</script>
过渡动画效果
使用Vue的transition组件添加切换动画:
<transition name="fade" mode="out-in">
<img :key="currentImage" :src="currentImage" alt="Slideshow">
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
自动轮播功能
添加定时器实现自动轮播:
mounted() {
this.startAutoPlay()
},
methods: {
startAutoPlay() {
this.timer = setInterval(() => {
this.nextImage()
}, 3000)
},
stopAutoPlay() {
clearInterval(this.timer)
}
}
使用第三方库
对于更复杂的需求,可以使用专用轮播库如vue-awesome-swiper:
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
Vue.use(VueAwesomeSwiper)
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(image, index) in images" :key="index">
<img :src="image">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
响应式图片处理
根据屏幕尺寸切换不同分辨率图片:

data() {
return {
responsiveImages: {
small: 'small.jpg',
medium: 'medium.jpg',
large: 'large.jpg'
}
}
},
computed: {
dynamicImage() {
const width = window.innerWidth
if (width < 768) return this.responsiveImages.small
if (width < 1024) return this.responsiveImages.medium
return this.responsiveImages.large
}
}






