思路
主要就是参考
实现轮播图。
实例
新建一个banner.vue通用组件。
代码如下:
<template>
<view>
轮播图
</view>
</template>
<script>
</script>
<style>
</style>
随后在index.vue中导入banner相关代码:
<template>
<view class="index-box">
<bannerVue></bannerVue>
</view>
</template>
<script>
import bannerVue from '../../components/common/banner.vue'
export default {
components: {bannerVue},
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
运行效果如下:
下面把图片放进去,在在static中新建images目录,如下图:
查询下swiper的相关文档
对swiper进行如下补充(修改banner.vue代码)并做一些css样式:
<template>
<view class="banner-box">
<view class="banner-bg"></view>
<swiper class="banner-swipper" indicator-dots indicator-color="#007aff"
indicator-active-color="#4cd964"
autoplay="4000">
<swiper-item class="swiper-item" v-for="(item, index) in bannerList" :key="index">
<image :src="item.imageUrl"></image>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default{
props: {
bannerList:{
type: Array,
default: () => [
{
id: 1,
imageUrl: '/static/images/01.png',
background: '#009B8C'
},
{
id: 2,
imageUrl: '/static/images/02.png',
background: '#729B8C'
}
]
}
}
}
</script>
<style lang="scss">
.banner-box{
padding-top: 60rpx;
.banner-bg{
position: absolute;
top: 0;
width: 100%;
height: 470rpx;
background-image: linear-gradient(red 50%, #FFF);
transform: .5s;
}
.banner-swipper{
width: 100%;
height: 350rpx;
.swiper-item{
width: 100%;
height: 100%;
image{
width: 100%;
height: 100%;
border-radius: 15rpx;
}
}
}
}
</style>
运行截图如下:
在此进行优化下:
<template>
<view class="banner-box">
<view class="banner-bg" :style="{'background-image': `linear-gradient(${bannerBackground || `#32DC2`} 50%, #FFF)`}"></view>
<swiper class="banner-swipper" indicator-dots indicator-color="#007aff"
indicator-active-color="#4cd964"
autoplay="4000"
circular
:current="current" @change="swiperChange">
<swiper-item class="swiper-item" v-for="(item, index) in bannerList" :key="index">
<image :src="item.imageUrl"></image>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default{
props: {
bannerList:{
type: Array,
default: () => [
{
id: 1,
imageUrl: '/static/images/01.png',
background: '#009B8C'
},
{
id: 2,
imageUrl: '/static/images/02.png',
background: '#729B8C'
}
]
}
},
data(){
return {
current: 0, //当前滑块的index
bannerBackground: '#009B8C' //背景色
}
},
methods:{
swiperChange(e){
// console.log(e.detail.current)
this.current = e.detail.current
this.bannerBackground = this.bannerList[this.current].background
}
}
}
</script>
<style lang="scss">
.banner-box{
padding-top: 60rpx;
.banner-bg{
position: absolute;
top: 0;
width: 100%;
height: 470rpx;
background-image: linear-gradient(red 50%, #FFF);
transform: .5s;
}
.banner-swipper{
width: 100%;
height: 350rpx;
.swiper-item{
width: 100%;
height: 100%;
padding: 0 30rpx;
box-sizing: border-box;
image{
width: 100%;
height: 100%;
border-radius: 15rpx;
}
}
}
}
</style>
运行截图如下: