1、directive/time.js
const vueTime = (Vue) => { Vue.directive('time', { bind(el, binding, vnode) { const endDate = binding.value; // 倒计时结束时间戳,毫秒 let timer = null; function updateCountdown() { const now = new Date().getTime(); if (now > endDate) { el.textContent = '00:00:00'; return; } const remainingTime = Math.floor((endDate - now) / 1000); const hours = Math.floor(remainingTime / 3600); const minutes = Math.floor((remainingTime % 3600) / 60); const seconds = remainingTime % 60; el.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } timer = setInterval(updateCountdown, 1000); // 清除定时器 vnode.context.$once('hook:beforeDestroy', () => { clearInterval(timer); }); // 立即执行一次以显示初始值 updateCountdown(); }, }); }; export default vueTime;
2、在main.js中全局引入time.js
3、使用:
<template> <div> <i v-time="1800000"></i> </div> </template>
标签:el,updateCountdown,const,自定义,倒计时,remainingTime,指令,endDate,Math From: https://www.cnblogs.com/chicidol/p/17970334