最近写项目遇到一个问题,页面中需要有用到倒计时,于是用了 setInterval ()手写了一个倒计时,后面用到页面中发现setInterval ()会引起页面卡顿,后来发现很多人遇到这个问题。原因是js的单线程引起的, 很多人说用setTimeout() 可以解决,后来发现并不管用。
后来发现把倒计时部分抽成组件,在放到页面中就不会再卡顿了。这里分享一下写的倒计时组件以及我在页面中的实际用法
组件代码:
<!-- /** * 组件描述: 倒计时组件 * $startTime 开始时间 * $endTime 结束时间 * $text 计时头部文案 * * 使用: ( * 1、php中注入组件 render('../components/countdown.php',['text' => '活动倒计时', 'startTime' =>$data['activityInfo']['startTime'],'endTime' => $data['activityInfo']['endTime']]) * 2、在页面对应位置加上自定义组件标签 <v-countdown></v-countdown> * 3、样式需要自己写 **/ --> <template id="vueCountdown"> <p class="cutdowntime"> <span class="text"><?=$text ?>:</span> <span class="time-number">{{countdown.days}}</span> <span class="time-text">天</span> <span class="time-number">{{countdown.hours}}</span> <span class="time-text">时</span> <span class="time-number">{{countdown.minutes}}</span> <span class="time-text">分</span> <span class="time-number">{{countdown.seconds}}</span> <span class="time-text">秒</span> </p> </template> <script> Vue.component('v-countdown', { template: '#vueCountdown', data: function(){ return Object.assign({ ctstartTime:'<?=$startTime ?>', ctendTime:'<?=$endTime ?>', countdownTimer: null, // 活动倒计时 countdown: { days: '00', hours: '00', minutes: '00', seconds: '00' }, }) }, mounted: function(){ const vm = this; //初始化配置 vm.addCountdown(); }, methods:{ // 添加倒计时 addCountdown: function () { const vm = this; var sDate = vm.ctstartTime; var eDate = vm.ctendTime; var beginTime = new Date(sDate).getTime(); var endTime = new Date(eDate).getTime(); if (new Date().getTime() >= endTime) return; // 活动已结束 // 活动未结束 vm.countdownTimer = setInterval(function () { var currentTime = new Date().getTime(); if (currentTime >= beginTime) { // 活动开始,计算倒计时 var date = vm.$dayjs.formateSeconds((endTime - currentTime) / 1000); var days = vm.$dayjs.fillZero(date.day); var hours = vm.$dayjs.fillZero(date.hour); var minutes = vm.$dayjs.fillZero(date.minute); var seconds = vm.$dayjs.fillZero(date.second); vm.countdown = { days: String(days), hours: String(hours), minutes: String(minutes), seconds: String(seconds), }; } if (currentTime > endTime) { // 活动结束,清除倒计时 vm.countdownTimer = null; clearInterval(vm.countdownTimer); } }, 1000); }, } }); </script>
复制
实际页面中的使用:
<?=$this->render('../components/countdown.php',['text' => $text, 'startTime' =>$coundownStartTime,'endTime' => $coundownEndTime])?> <div class="timer flex-center" v-if="activityStatus == 0"> <v-countdown></v-countdown> </div>
复制