一 效果图
我实现的效果是自动轮播,三秒钟转换一次,故没有左右滑动,如果需要滑动效果需要自己添加相应的动作元素
轮播图视频
二 实现代码
<template>
<div class="carousel">
<div @click="prevSlide" class="carousel-prev-icon-left"></div>
<div class="carousel-slides">
<img
v-for="(image, index) in images"
:key="index"
v-if="image"
:src="require(`@/assets/img/${image}`)"
:style="{left: index * 100 + '%', 'transform': dynamicstyle}"
alt="暂无图片"
/>
</div>
<div @click="nextSlide" class="carousel-prev-icon-right"></div>
</div>
</template>
<script>
export default {
data() {
return {
images: [
'消防1.jpg',
'消防2.jpg',
'消防3.jpg'
// ... 更多图片
],
dynamicstyle: "", //动态样式
currentSlide: 0, //播放序号
interval: null,
}
},
mounted() {
// 自动播放动画
this.startSlideshow()
},
methods: {
nextSlide() {
// 每次指针加一
this.currentSlide = (this.currentSlide + 1) % this.images.length
this.setStyle();
},
prevSlide() {
// 每次减一,为负数时循环
this.currentSlide = (this.currentSlide - 1 + this.images.length) % this.images.length;
this.setStyle();
},
// 图片动画
setStyle() {
this.dynamicstyle = `translatex(-${this.currentSlide*100}%)`
},
// 定时器
startSlideshow() {
this.interval = setInterval(() => {
this.currentSlide = (this.currentSlide + 1) % this.images.length;
this.setStyle();
}, 3000)
},
// startSlideshow(),用于启动一个轮播功能。
stopSlideshow() {
clearInterval(this.interval)
}
}
}
</script>
<style scoped>
/*特殊的样式标签。它用于给组件的样式设置局部作用域,只影响当前组件的样式,而不会影响其他组件或全局样式。*/
.carousel {
/*width: 200px;*/
position: relative;
top:-40px;
left: -420px;
}
.carousel-slides {
top: -20px;
position: relative;
width: 556px;
height: 460px;
overflow: hidden;
}
.carousel-slides img {
display: inline-block;
position: absolute;
width: inherit;
margin: 0;
padding: 0;
top: 0;
left: 0;
height: 100%;
transition: 0.5s transform ease-in-out;
}
.carousel-prev-icon-left {
position: relative;
left: 0px;
top: -55px;
height: 50px;
width: 40px;
border: none;
background-image: url(../../assets/body.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: center;
z-index: 999;
/*控制元素在堆叠上下文中的显示顺序,即元素在垂直方向上的叠放次序*/
}
.carousel-prev-icon-right {
position: absolute;
right: 0px;
top: -55px;
height: 50px;
width: 40px;
border: none;
background-image: url('../../assets/body.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
z-index: 999;
}
</style>
三 补充说明1
如果需要在其他的页面引入此轮播图步骤
3.1 目标界面引入1
首先在引入的界面的script引入
import Lu from ".//l.vue";
3.2 目标界面引入2
首先在引入的界面的script的export default引入
components:{Lu},
3.3 目标界面引入3
最后在界面写入相应的组件
<Lu></Lu>
四 补充说明2
图片路径和图片名称需要更改,图片需要放置在images数组中,且图片路径最好是相对路径