Vue数据列表倒计时展示

 

 

 

 

 

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.13.2/lib/index.js"></script>
<template>
   <div class="all" ref="providall">
        <el-table stripe height="calc(100vh - 240px)" class="mt-10" v-for="(item) in iconlistall" >
          <el-table-column>
            <div v-if="item.pre_at > 0">计时:{{time(item.pre_at)}}</div>
            <div v-else>计时: 已超时</div>
          </el-table-column>
        </el-table>
   </div>
</template>

<script>
export default {
  data() {
    return {
      iconlist: [],
      ticker: null,
      d: "",
      h: "",
      m: "",
      s: ""
    };
  },
  computed:{ //这里是监听自定义数组的变化 因为有一个计时器每秒都会减去数组中字段的时间 所以 数组是每秒更新的
    iconlistall:{
      get(){
        return this.iconlist
      }
    }
  },
  methods: {
    createds() {
    //这里是假的数据
      let list = [
        {
          pre_at: "2020-06-03 11:18:23",
          address:"测试1",
        },
        {
          pre_at: "2020-06-01 16:18:35",
          address:"测试2",
        },
        {
          pre_at: "2020-06-04 6:14:42",
          address:"测试3",
        }
      ];
      //首先循环数组 在 正常的情况下这个数组是后台传递过来的 然后将这个数组中的最后截止时间减去当前时间获得时间戳
      for (let i = 0, len = list.length; i < len; i++) {
        const item = list[i];
        item.pre_at = new Date(item.pre_at).getTime() - new Date().getTime();
      }
      this.iconlist = list; //将改变后的数组赋值给自定义的数组 然后调用计时器 每秒减去指定字段的时间戳 -1000毫秒
      if (this.ticker) { //这一段是防止进入页面出去后再进来计时器重复启动
        clearInterval(this.ticker);
      }
      this.beginTimer(); //启动计时器减指定字段的时间
    },
    beginTimer() { //这个计时器是每秒减去数组中指定字段的时间
      this.ticker = setInterval(() => {
        for (let i = 0, len = this.iconlist.length; i < len; i++) {
          const item = this.iconlist[i];
          if (item.pre_at > 0) {
            item.pre_at = item.pre_at - 1000;
          }
        }
      }, 1000);
    },
    time(time) { //这个函数是每秒把时间重新计算下
      if (time >= 0) {
        let d = Math.floor(time / 1000 / 60 / 60 / 24);
        let h = Math.floor((time / 1000 / 60 / 60) % 24);
        let m = Math.floor((time / 1000 / 60) % 60);
        let s = Math.floor((time / 1000) % 60);
         return '还有'+d+'天'+h+'时'+m+'分'+s+'秒';
      }
    },
  },

  mounted() {
    this.createds()
  },
  destroyed() {}
};
</script>

posted @ 2020-05-26 15:46  JOEH60  阅读(1921)  评论(0编辑  收藏  举报