效果图
后端返回数据格式
info:{
vip_validity:"2027-09-07"
}
<div>
到期时间:{{ info.vip_validity }}, 剩余
<span :class="countdownDays(info.vip_validity) < 7 ? 'surplus' : ''">
{{ !!info.vip_validity ? countdownDays(info.vip_validity) : 0 }}
</span>天
</div>
js
computed:{
// 计算相差天数
countdownDays(timeStr) {
const endDate = new Date(timeStr).getTime(); // 时间戳
const now = new Date().getTime();
const dateDiff = endDate - now; // 时间差(毫秒)
if (isNaN(dateDiff) || dateDiff < 0) {
return 0; // 如果输入的日期不合法或小于0,返回0
}
return Math.floor(dateDiff / (1000 * 60 * 60 * 24)); // 转换为天数
},
}
css
.surplus {
color: #ff4d4f;
font-weight: 800;
font-size: 18px;
}