1、使用npm安装moment
npm install moment --save
2、main.js中
import moment from 'moment'
Vue.config.productionTip = false
Vue.prototype.$moment = moment
moment.locale('zh-cn')
3、所应用的.vue页面
<template>
<div>
<div>输入格式为:YYYY-MM-DD HH:MM:SS</div><br/>
<div>例如:2022-07-21 16:00:00</div><br/>
<input class="input" v-model="dataValue" placeholder="请输入日期" />
<button class="btn" @click="computeAction">计算</button>
<div>倒计时:{{time}}</div>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
dataValue: '',
time: ''
}
},
mounted () {
},
methods: {
computeAction () {
let startT = this.$moment(new Date())
let endT = this.$moment(new Date(this.dataValue))
let diffT = endT.diff(startT)
let time = `${this.$moment.duration(diffT).years()} 年 ${this.$moment.duration(diffT).months()} 月 ${this.$moment.duration(diffT).days()} 日 ${this.$moment.duration(diffT).hours()} 时 ${this.$moment.duration(diffT).minutes()} 分 ${this.$moment.duration(diffT).seconds()}秒`
this.time = time
}
}
}
</script>
<style scoped>
.input {
width: 300px;
padding: 10px;
border: 0;
outline: 0;
-webkit-appearance: none;
background-color: transparent;
font-family: PingFangSC-Medium;
font-weight: 500;
font-size: 20px;
color: rgba(0, 0, 0, 0.90);
letter-spacing: 0;
line-height: 20px;
caret-color: #0DC060;
border-radius: 4px;
background: #F5F5F5;
border: 1px solid rgba(0, 0, 0, 0);
box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0);
margin: 0 10px;
}
.btn {
display: block;
width: 160px;
height: 48px;
line-height: 48px;
border-radius: 6px;
font-size: 16px;
background-color: #0dc060;
color: #fff;
border: 0;
margin: 20px auto;
}
</style>
4、效果图: