本文实例为大家分享了Vue实现首页banner自动轮播的具体代码,供大家参考,具体内容如下
效果如图:
①创建Banner.vue组件,需传入banner数组,可设置轮播间隔ms
<template>
<div class="m-banner-wrap" v-if="bannerData.length">
<div class="m-banner-list">
<div
class="u-banner-item fade"
v-for="(item, index) in bannerData"
:key="index"
v-show="index===activeIndex"
:style="`background: url(${item.tupian}) no-repeat; background-size: cover;`"
@mouseover="onOver()" @mouseout="onOut()">
<a :href="item.link"></a>
</div>
</div>
<div class="m-dot-list" v-if="bannerData.length > 1">
<div v-for="(item, index) in bannerData" :key="index" :class="['u-dot-item', {active: index===activeIndex}]" @mouseenter="onEnter(index)" @mouseleave="onLeave">
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Banner',
props: {
bannerData: { // banner数组
type: Array,
default: () => {
return []
}
},
interval: { // 切换间隔ms
type: Number,
default: 3000
}
},
data () {
return {
activeIndex: 0,
timer: null
}
},
mounted () {
setTimeout(() => {
this.startSlider()
}, 1000)
},
methods: {
onOver () {
clearInterval(this.timer)
},
onOut () {
this.startSlider()
},
onEnter (index) {
this.activeIndex = index
clearInterval(this.timer)
},
onLeave () {
this.startSlider()
},
startSlider () {
clearInterval(this.timer)
if (this.bannerData.length > 1) {
this.timer = setInterval(this.onMove, this.interval)
}
},
onMove () {
if (this.activeIndex === this.bannerData.length - 1) {
this.activeIndex = 0
} else {
this.activeIndex++
}
}
},
beforeDestroy () {
clearInterval(this.timer)
this.timer = null
}
}
</script>
<style lang="less" scoped>
@mainColor: #108ee9;
.m-banner-wrap {
width: 100%;
height: 600px;
min-width: 1200px;
margin: 0 auto;
overflow: hidden;
position: relative;
.m-banner-list {
height: 600px;
.u-banner-item {
min-width: 1200px;
height: 600px;
width: 100%;
a {
display: block;
height: 100%;
}
}
.fade {
animation: fade 0.5s ease-in-out; // 切换banner时的过渡效果
}
@keyframes fade {
0% {opacity:0;}
5% {opacity:0.05;}
10% {opacity:0.1;}
20% {opacity:0.2;}
35% {opacity:0.35;}
50% {opacity:0.5;}
65% {opacity:0.65;}
80% {opacity:0.8;}
90% {opacity:0.9;}
95% {opacity:0.95;}
100%{opacity:1;}
}
}
.m-dot-list {
width: 600px;
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -300px;
text-align: center;
.u-dot-item { // 圆点样式
display: inline-block;
width: 12px;
height: 12px;
margin: 0 5px;
background: #fff;
cursor: pointer;
border: 1px solid #fff;
border-radius: 50%;
opacity: 0.8;
}
.active { // 圆点选中样式
width: 30px;
background: @mainColor;
border: 1px solid @mainColor;
border-radius: 12px;
opacity: 1;
}
}
}
</style>
②在要使用的页面引入
<Banner :bannerData="bannerData" :interval="3000"/>
import Banner from '@/components/Banner'
components: {
Banner
}
data () {
return {
bannerData: [
{
link: '跳转地址...',
src: '图片地址...'
},
{
link: '跳转地址...',
src: '图片地址...'
},
{
link: '跳转地址...',
src: '图片地址...'
}
]
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。