vue中根据倒计时来排序的模块

**

vue中根据倒计时来排序的模块

一、原理分析

此demo是实现多条数据的有效时间,通过数据的有效时间来进行排序,从而进行倒计时,倒计时归零后将自动删除此模块
实现思路为将时间戳转换为可视时间,通过set方式添加到数组对象中,然后通过sort方式来进行排序

二、代码展示

<template>
  <div class="hello">
    <ul>
      <li v-for="(item,index) in list1" :key="index">
        <div class="item">
          <p>{{item.title}}</p>
          <time>{{item.djs}}</time>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
function InitTime(endtime) {   //首次进入页面显示的时间数据
  var dd,
    hh,
    mm,
    ss = null;
  var time = parseInt(endtime) - new Date().getTime() / 1000;
  if (time <= 0) {
    return "结束";
  } else {
    dd = Math.floor(time / 60 / 60 / 24);
    hh = Math.floor((time / 60 / 60) % 24);
    mm = Math.floor((time / 60) % 60);
    ss = Math.floor(time % 60);
    var str = dd + "天" + hh + "小时" + mm + "分" + ss + "秒";
    return str;
  }
}
export default {
  data() {
    return {
      ssss: [  
        {
          title: "第一条数据",
          time: "1589901180"    //时间戳(可以使后台传过来的)
        },
        {
          title: "第二条数据",
          time: "1589902921"
        },
        {
          title: "第三条数据",
          time: "1589902321"
        },
        {
          title: "第四条数据",
          time: "1589902921"
        }
      ],
      list: []
    };
  },
  created() {
    console.log(new Date().getTime());
    var ssss = this.ssss;
    ssss.map(obj => {
      this.$set(obj, "djs", InitTime(obj.time));   //把时间添加到数组对象中
    });
    this.list = ssss;
  },
  mounted() {
    setInterval(() => {     //倒计时
      for (var key in this.list) {
        var aaa =
          parseInt(this.list[key]["time"]) - new Date().getTime() / 1000;
        if (aaa > 0) {
          var dd = Math.floor(aaa / 60 / 60 / 24);
          var hh = Math.floor((aaa / 60 / 60) % 24);
          var mm = Math.floor((aaa / 60) % 60);
          var ss = Math.floor(aaa % 60);
          this.list[key]["djs"] =
            dd + "天" + hh + "小时" + mm + "分" + ss + "秒";
        } else {
          this.list.splice(key, 1);
        }
      }
    }, 1000);
  },
  methods: {
    sortKey(array, key) {        //排序事件
      return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return x < y ? -1 : x > y ? 1 : 0;
      });
    }
  },
  computed: {
    list1: function() {
      return this.sortKey(this.list, "time");//排序打印
    }
  }
};
</script>

<style scoped>
ul {
  margin: 0;
  padding: 0;
  display: flex;
}
li {
  list-style: none;
  flex: 1;
  padding: 10px;
}
.item {
  background: #666;
  border-radius: 10px;
  height: 200px;
  color: white;
}
</style>

三、结语

非常实用的一个小功能,希望对你的项目有所帮助

猜你喜欢

转载自blog.csdn.net/qyp_1/article/details/106275123