<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue實時顯示當前時間顯示</title> <link rel="stylesheet" href="../css/reset.css"> <script src="../js/jquery/jquery-3.1.1.min.js"></script> <script src="../js/vue/vue.js"></script> </head> <body > <div id="app">當前實時時間:{{dateFormat(date)}}</div> <script> var vm=new Vue({ el:"#app", data:{ date:new Date() }, mounted () { var _this = this; //聲明一個變量指向vue實例this,保證作用域一致 this.timer = setInterval(function() { _this.date = new Date();//修改數據date }, 1000); }, beforeDestroy () { if(this.timer) { clearInterval(this.timer);//在vue實例銷毀錢,清除我們的定時器 } }, methods:{ //時間格式化函數,此處僅針對yyyy-MM-dd hh:mm:ss 的格式進行格式化 dateFormat(time) { var date=new Date(time); var year=date.getFullYear(); /* 在日期格式中,月份是從0開始的,因此要加0 * 使用三元表達式在小於10的前面加0,以達到格式統一 如 09:11:05 * */ var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1; var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate(); var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours(); var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes(); var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds(); // 拼接 return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds; } } }) </script> </body> </html>