需求场景:
swiper默认展示第二项,然后在change的时候,判断如果当前项等于0 就给数组最前面插入一项
最关键的两点:
- 在swiper的最外层 加 v-if=“swipershow”
<u-swiper v-if="swipershow" :list="list" :current="current" @change="change" :autoplay="false"></u-swiper>
- 在改变swiper数据后重新渲染swiper组件
this.swipershow = false;
this.$nextTick(() => {
this.swipershow = true;
});
完整代码:
<template>
<view class="wrap">
<u-swiper v-if="swipershow" :list="list" :current="current" @change="change" :autoplay="false"></u-swiper>
</view>
</template>
<script>
export default {
data() {
return {
list: [{
image: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
title: '昨夜星辰昨夜风,画楼西畔桂堂东'
},
{
image: 'https://cdn.uviewui.com/uview/swiper/2.jpg',
title: '身无彩凤双飞翼,心有灵犀一点通'
},
{
image: 'https://cdn.uviewui.com/uview/swiper/3.jpg',
title: '谁念西风独自凉,萧萧黄叶闭疏窗,沉思往事立残阳'
}
],
current:1,
swipershow:true
}
},
methods: {
change(e){
console.log('e',e)
if (e == 0) {
let data = {
image: 'https://cdn.uviewui.com/uview/swiper/3.jpg',
title: '第一页'
}
this.list.unshift(data)
this.swipershow = false;
this.$nextTick(() => {
this.swipershow = true;
});
}
}
}
}
</script>
<style lang="scss" scoped>
.wrap {
padding: 40rpx;
}
</style>