vue 2.1.3 实时显示当前时间,每秒更新

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>Vue</title>    
 6     </head>
 7     <body>    
 8         <div id="app">
 9             {{date}}
10         </div>
11         <!-- 开发环境版本,包含了用帮助的命令行警告 -->
12         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
13         <script type="text/javascript">        
14             var app = new Vue({
15                 el:'#app',
16                 data:{
17                     date: new Date()
18                 },
19                 mounted () {
20                     var _this = this; //声明一个变量指向vue实例this,保证作用域一致
21                     this.timer = setInterval(function() {
22                         _this.date = new Date();//修改数据date
23                     }, 1000);
24                 },
25                 beforeDestroy () {
26                     if(this.timer) {
27                         clearInterval(this.timer);//在vue实例销毁钱,清除我们的定时器
28                     }
29                 }               
30             });
31             
32         </script>
33     </body>
34 </html>

 

posted @ 2018-06-04 16:39  铜镜123  阅读(8849)  评论(0编辑  收藏  举报