该组件应用场景,例如单个页面需要多个倒计时的时候,该组件就派上用场了。
因不同的项目,需求不同,微调一下代码即可用。本实例代码的实际场景是,用户在规定时间点内需要有个操作,倒计时的时间其实是
规定的时间-(当前时间-历史时间的一个节点)。组件代码为完整代码,复制即可用,欢迎批评指正~~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<template> <p class="countDown" v-html="newSeconds"></p> </template> <script> export default { data(){ return{ time: '', recive: '', } }, props: ['seconds', 'reciveTime'], created(){ this.time = this.seconds; this.recive = this.reciveTime; }, computed: { newSeconds: { get: function(){ let self = this; let stime = self.recive - self.time; if(stime <= 0 || self.recive < stime){ return self.newSeconds = '<b>00</b>:<b>00</b>:<b>00</b>'; } let h=parseInt((stime/3600)%24); if(h < 10) h = '0'+h; let m=parseInt((stime/60)%60); if(m < 10) m = '0'+m; let s=parseInt(stime%60); if(s < 10) s = '0'+s; return self.newSeconds = '<b>'+h+'</b>:<b>'+m+'</b>:<b>'+s+'</b>'; }, set: function(){ } } }, mounted(){ let self = this; let timer = setInterval(function(){ self.time++; if(self.recive < self.time){ clearInterval(timer); } }, 1000); }, methods: {}, } </script> |
在页面内调用方法
1 2 3 4 5 6 7 8 9 10 11 |
<timer :seconds='now-pay_time' :reciveTime="reciveTime"></timer> <script> import timer from '../components/common/timer' components: { timer }, data () { return { reciveTime: null, now: parseInt(new Date().getTime()/1000), } }, </script> |
效果图