在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//大於父子組件每一秒渲染時間也可以正常使用 }; },