自定义指令-倒计时

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>

 

posted @ 2024-01-17 16:23  chicidol  阅读(12)  评论(0编辑  收藏  举报