vue swiper 动态加载/插入数据时,默认跳到第0项,问题解决

25 篇文章 0 订阅
需求场景:
swiper默认展示第二项,然后在change的时候,判断如果当前项等于0 就给数组最前面插入一项
最关键的两点:
  1. 在swiper的最外层 加 v-if=“swipershow”
<u-swiper v-if="swipershow" :list="list" :current="current" @change="change" :autoplay="false"></u-swiper>
  1. 在改变swiper数据后重新渲染swiper组件
 this.swipershow = false; //先隐藏
  //等数据加载完毕后,重新渲染swiper
  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  //控制swiper显示隐藏
			}
		},
		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; //先隐藏
                    //等数据加载完毕后,重新渲染swiper
                    this.$nextTick(() => {
                        this.swipershow = true;
                    });
                }
            }
		}
	}
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 40rpx;
	}
</style>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值