vue实时显示当前时间且转化为“yyyy-MM-dd hh:mm:ss”格式笔记

 1 DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>vue实时显示当前时间显示title>
 6     <link rel="stylesheet" href="../css/reset.css">
 7     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
 8     <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js">script>
 9 head>
10 <body >
11 <div id="app">当前实时时间:{{dateFormat(date)}}div>
12 <script>
13     var vm=new Vue({
14         el:"#app",
15         data:{
16             date:new Date()
17         },
18         mounted () {
19             var _this = this; //声明一个变量指向vue实例this,保证作用域一致
20             this.timer = setInterval(function() {
21                 _this.date = new Date();//修改数据date
22             }, 1000);
23         },
24         beforeDestroy () {
25             if(this.timer) {
26                 clearInterval(this.timer);//在vue实例销毁钱,清除我们的定时器
27             }
28         },
29         methods:{
30             //时间格式化函数,此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
31             dateFormat(time) {
32                 var date=new Date(time);
33                 var year=date.getFullYear();
34                 /* 在日期格式中,月份是从0开始的,因此要加0
35                  * 使用三元表达式在小于10的前面加0,以达到格式统一  如 09:11:05
36                  * */
37                 var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
38                 var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
39                 var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
40                 var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
41                 var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
42                 // 拼接
43                 return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
44             }
45         }
46     })
47 script>
48 body>
49 html>

 vue实时显示当前时间且转化为“yyyy-MM-dd hh:mm:ss”格式笔记_第1张图片

你可能感兴趣的:(vue实时显示当前时间且转化为“yyyy-MM-dd hh:mm:ss”格式笔记)