1. Install my moment. Js
npm install moment
Copy the code
2. Import it on the page.
- You can write the countdown on a component and then introduce it in the component alone
const moment = require('moment');
//moment() The current time
//moment().valueOf(); The timestamp of the current time, in milliseconds
Copy the code
- It can also be introduced in main.js and added to the Vue prototype chain; (THIS is what I use)
const moment = require('moment');
Vue.prototype.$moment = moment;
//this.$moment()
//this.$moment().valueOf(); The timestamp of the current time, in milliseconds
Copy the code
3. Obtain startTime and endTime from the background and determine whether they are in the active range
//this. Showtime is the timestamp of the countdown
//this.status is the active state
let currentTime = this.$moment().valueOf();
if(currentTime < startTime){
// The activity has not started
this.this.status = 0
let t = startTime - currentTime;
let time = setInterval(() = > {
t -= 1000;
this.showtime = t
},1000)}else if(currentTime > startTime && currentTime < endTime){
// The event is in progress
this.status = 1;
let t = endTime - currentTime;
let time = setInterval(() = > {
t -= 1000;
this.showtime = t
},1000)}else{
// Do the operation after the activity ends
this.status = 2;
}
Copy the code
4. Write the time on the page
//timeValue filters are preceded by "0" for values less than 10;
//filters:{
//timeValue(val)
//{if(val<10) return '0'+val;
//return val; }
/ /}
<span class="remindtext">{{status == 0? 'There's still time to go.':status == 1?'Just short of the end':'Activity is over'}}</span>
<span class="times" v-if="status == 0 || status == 1">
<b>{{$moment.duration(showtime).days() | timeValue}}</b>
<b>day</b>
<b>{{$moment.duration(showtime).hours() | timeValue}}</b>
<b>:</b>
<b>{{$moment.duration(showtime).minutes() | timeValue}}</b>
<b>:</b>
<b>{{$moment.duration(showtime).seconds() | timeValue}}</b>
</span>
Copy the code