vue.js实战——vue 实时时间

created:实例创建完成后调用,此阶段完成了数据的观测等,但尚未挂载,$el还不可用,需要初始化处理一些数据时会比较有用。

mounted:el挂载到实例上后调用,一般我们的第一个业务逻辑会在这里开始。

beforeDestroy:实例销毁之前调用,主要解绑一些使用addEventListener监听的事件等。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>实时时间</title>
    <script src="vue.js"></script>
</head>
<body>
    <div id="app">
        {{date}}
    </div>
    <script>
        //自个写的
    /*     new Vue({
            el:"#app",
            data:{
                date:''
            },
            mounted:function(){
                var self=this;
                var time=setInterval(function(){
                    self.date=new Date();
                },1000);
            },
            beforeDestory:function(){
                clearInterval(time);
            }
        }) */
        //标准代码
        var app=new Vue({
            el:'#app',
            data:{
                date:new Date()
            },
            mounted:function(){ //el挂载到实例上调用,一般我们第一个业务逻辑会在这里开始
                var _this=this;
                this.timer=setInterval(function(){
                    _this.date=new Date();
                },1000);
            },
            beofreDestory:function(){
                if(this.timer){
                    clearInterval(this.timer);
                }
            }
        })
    </script>
</body>
</html>
对比之下自己写的代码真的是,考虑的太少了,都没有判断setInterval对象是否存在
原文地址:https://www.cnblogs.com/em2464/p/10405273.html