前端界面顯示當前時間的Vue代碼


<!DOCTYPE html> 
<html> 
<head> <meta charset="utf-8">
    <title>Vue 示例</title>
</head> 
<body>
    <div id="app" >
      {{ date | formatDate }}
    </div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
    var padDate = function(value){
        return value < 10 ? '0' + value :value;
    }
    var app = new Vue({
        el: '#app',
        data: {
            date: new Date()
        },
        filters: {
            formatDate: function (value) {
                var date = new Date(value);
                var year = date.getFullYear();
                var month = padDate(date.getMonth() + 1);
                var day = padDate(date.getDay());
                var hours = padDate(date.getHours());
                var minutes = padDate(date.getMinutes());
                var seconds = padDate(date.getSeconds());
                // 整理並返回
                return year + '-' + month + '-' + day + '-' + hours + '?' + minutes + '?' + seconds;
            }
        },
        mounted: function () {
            var _this = this; // 指向this 變量作用域一致;
            this.timer = setInterval(function() {
                _this.date = new Date(); // 修改date
            },1000);
        },
        beforeDestroy: function() {
            if (this.timer) {
                clearInterval(this.timer);
            }
        }
        // created: function () {
        //     console.log(this.a);
        // },
        // mounted: function () {
        //     var _this = this; //聲明一個變量指向 Vue 實例 this,保證作用域一致
        //     this.timer = setInterval (function () {
        //         this.date = new Date();
        //         console.log(this.date);// 修改date
        //     },1000);
            
        // },
        // beforeDestory: function () {
        //     if (this.timer) {
        //         clearInterval(this.timer);  //在 Vue 實例銷毀前,清除我們的定時器

        //     } 
        // }
    })
</script>
</body>
</html>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM