1.创建countdown.vue文件:
<template><p style="font-size: 10px">{{time}}</p>
</template>
<script>export default{data () {return {time : '',flag : false}},mounted () {let time = setInterval(() => {if (this.flag == true) {clearInterval(time);}this.timeDown();}, 500);},props : {endTime : {type: String},index : {type: Number}},methods : {timeDown () {const endTime = new Date(this.endTime);const nowTime = new Date();let leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);let d = parseInt(leftTime / (24 * 60 * 60));let h = this.formate(parseInt(leftTime / (60 * 60) % 24));let m = this.formate(parseInt(leftTime / 60 % 60));let s = this.formate(parseInt(leftTime % 60));if(leftTime <= 0){this.flag = true;this.time = '00:00:00';//在这里传给父组件leftTime,全局传递的话倒计时没结束会有很多数据。this.$emit('update:leftTime', this.time,this.index);}else{this.time = `${d}:${h} :${m} :${s} `; }},formate(time) {if (time >= 10) {return time;} else {return `0${time}`;}}}}
</script>
<style scoped>
</style>
2.在页面中使用该组件:
根据循环项的index控制类名显示与否,index%2==0 偶数项,反则奇数项。endTimeStatus[index]倒计时结束的项。
<template>
....
<div :class="index%2==0 ? (endTimeStatus[index] ? 'roomitem-end' : 'roomitem') : (endTimeStatus[index]? 'roomitem-end' : 'roomitem2')" v-for="(item,index) in RoomList" :key="item.id" @click="goroom(item.id)"><countdown :endTime='item.end_time' :index='index' @update:leftTime="parentMethod"></countdown></div>
....
</template><script>
import countdown from "./countdown.vue";
export default {components: {countdown},methods: {parentMethod(leftTime, index) {// 操作倒计时组件传递过来的参数this.itemLeftTimes[index] = leftTime;this.endTimeStatus[index] = true;//一定要刷新RoomList数据this.GetRooms();},
}