在vue中使用跑马灯(这里用了antdesign vue 的a-carousel)
出现的问题:1:当跑马灯自动播放设置时间 autoplaySpeed 大于接近自定义的定时器时间时,跑马灯失效。
当小于时间会再次跑起:
跑马灯: <a-carousel arrows autoplay :autoplaySpeed="autoplaySpeed"> <div style="background: red; overflow: hidden"> <hotmap></hotmap> </div> <div style="background: blue; overflow: hidden"> <hotmap2></hotmap2> </div> </a-carousel> 时间: computed:{ autoplaySpeed(){ return 1000 } }, 另外显示展示时间的定时器: getTimer() { this.timeInterval = setInterval(() => { var date = new Date(); var year = date.getFullYear(); //获取当前年份 var mon = date.getMonth() + 1; //获取当前月份 var da = date.getDate(); //获取当前日 var day = date.getDay(); //获取当前星期几 if (day == "0") { day = "日"; } if (day == "1") { day = "一"; } if (day == "2") { day = "二"; } if (day == "3") { day = "三"; } if (day == "4") { day = "四"; } if (day == "5") { day = "五"; } if (day == "6") { day = "六"; } var h = date.getHours(); //获取小时 var m = date.getMinutes(); //获取分钟 var s = date.getSeconds(); //获取秒 this.timeYear = document.getElementById("timeOfYear"); this.timeMonth = document.getElementById("timeOfWeek"); this.timeYear = year + "年" + mon + "月" + da + "日"; this.timeMonth = "星期" + day + " " + h + ":" + m + ":" + s; }, 3001); }, 挂载执行: mounted() { this.$nextTick(() => { this.getTimer(); this.ajaxInit(); }); }, 离开销毁: destroyed() { clearInterval(this.timeInterval); this.timeInterval = null; },
这里只要轮播时间大于等于甚至接近定时器设置的时间,轮播图就会失效停止播放
分析原因:
网上相关资料很少,自己多次测试确实有这种bug,主要原因分析:轮播设置的定时器正常轮播后,自己自定义的显示时间的定时器1s后更新了数据,从而引起页面重新渲染绘制,这样就
导致了轮播组件a-carousel的speed数据重新更新,即便是没有改变值,组件a-carousel自动播放的初始值还是变为初始化,还没等到时间开始轮播1s后再次被刷新数据导致一直不会轮播
解决:
分析因为是一个组件内渲染数据刷新date更新组件,可以把swiper单独抽离出来作为组件这样父组件渲染页面的定时器就不会影响到子组件carouse轮播的使用
代码参考:
父组件: <!-- 地图 --> <div class="mapContain"> <myswiper></myswiper> </div> import myswiper from "../components/charts/myswiper"; emthods:{ getTimer(){ ... } } mounted(){ this.$nextTick(() => { this.getTimer(); this.ajaxInit(); });} 抽离后的子组件: <a-carousel arrows autoplay :autoplaySpeed="autoplaySpeed"> <!-- <hotmap></hotmap> --> <!-- <hotmap2></hotmap2> --> <div style="background:; overflow: hidden"> <hotmap></hotmap> </div> <div style="background:; overflow: hidden"> <hotmap2></hotmap2> </div> </a-carousel> data() { return { timer: null, autoplaySpeed:3000//大于父子组件每一秒渲染时间也可以正常使用 }; },