vueでカウントダウン機能を作成する


vueで簡単なカウントダウンを作る
  • カウントダウンの核心は再帰的にタイマーを実現することであるので、方法ではsettimeoutを使えばよい
  • .
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    
    <body>
    	<div id="app">
    		<div class="timeruning">{{day}} {{hr}}:{{min}}:{{sec}}</div>
    	</div>
    </body>
    <script>
    	var vm = new Vue({
    		el: "#app",
    		data: {
    			day: 0,
    			hr: 0,
    			min: 0,
    			sec: 0
    		},
    		mounted: function () {
    			this.countdown()
    		},
    		methods: {
    			countdown: function () {
    				//        
    				const end = Date.parse(new Date('2019-8-12 10:10:10'))
    				//        
    				const now = Date.parse(new Date())
    				//             0
    				if (now >= end) {
    					this.day = 0
    					this.hr = 0
    					this.min = 0
    					this.sec = 0
    					return
    				}
    				//                    
    				const msec = end - now
    				let day = parseInt(msec / 1000 / 60 / 60 / 24) //    
    				let hr = parseInt(msec / 1000 / 60 / 60 % 24)//     
    				let min = parseInt(msec / 1000 / 60 % 60)//     
    				let sec = parseInt(msec / 1000 % 60)//    
    				//     
    				this.day = day
    				this.hr = hr > 9 ? hr : '0' + hr
    				this.min = min > 9 ? min : '0' + min
    				this.sec = sec > 9 ? sec : '0' + sec
    				//  this  
    				const that = this
    				//                                
    				setTimeout(function () {
    					that.countdown()
    				}, 1000)
    			}
    		}
    
    	})
    </script>