vue如何动态实时的显示时间浅析

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文档点这里

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>

附:vue时间戳 获取本地时间,实时更新

<template>
	<p>当前时间:{{nowTime}}</p>
</template>

<script>
	export default{
		data(){
			return{
				nowTime:\"\"
			}
		},
		methods:{
			getTime(){
				setInterval(()=>{
					//new Date() new一个data对象,当前日期和时间
					//toLocaleString() 方法可根据本地时间把 Date 对象转换为字符串,并返回结果。
					this.nowtime = new Date().toLocaleString();
				},1000)
			}
		},
		created(){
			this.getTime();
		}
	}
</script>

vue如何动态实时的显示时间浅析

总结

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容