vue动态实时的显示时间


有两种方法

1.可以用day.js,处理日期和时间的js库

用法 npm install dayjs --save

引入import dayjs from 'dayjs'

然后创建定时器更新最新的时间

this.timeId = setInterval(()=>{

   this.sday =dayjs().format('YYYY-MM-DD HH:mm:ss');

}, 1000);

更多的详情可以查看day.js的api   

api文档点这里https://github.com/iamkun/dayjs/blob/master/docs/zh-cn/API-reference.md

2.使用vue过滤器filters

<template>
  <el-container id="box">
       {{ date | formaDate }}
  </el-container>
</template>
<script>
 //创建一个函数来增加月日时小于10在前面加0
   var padaDate = function(value){
      return value<10 ? '0'+value : value;
   };
export default {
  data() {
    return {
      date: new Date(), //实时时间
    };
  },
  watch: {
   
  },
  computed: {},
  filters:{
    //设置一个函数来进行过滤
    formaDate:function(value){
       //创建一个时间日期对象
       var date = new Date();
       var year = date.getFullYear();      //存储年
       var month = padaDate(date.getMonth()+1);    //存储月份
       var day = padaDate(date.getDate());         //存储日期
       var hours = padaDate(date.getHours());      //存储时
       var minutes = padaDate(date.getMinutes());  //存储分
       var seconds = padaDate(date.getSeconds());  //存储秒
       //返回格式化后的日期
       return year+''+month+''+day+''+hours+''+minutes+''+seconds+'';
     }
  },
  methods: {
   
  },
  created() {
    
  },
  mounted() {
    //创建定时器更新最新的时间
    var _this = this;
    this.timeId = setInterval(function() {
      _this.sday =dayjs().format('YYYY-MM-DD HH:mm:ss');
    }, 1000);
    this.initmap();
  },
  beforeDestroy: function() {
    //实例销毁前青出于定时器
    if (this.timeId) {
      clearInterval(this.timeId);
    }
  }
};
</script>
<style lang="scss" scoped>

</style>

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM