Vue.js 中使用 reactive 对象和定时器实现倒计时功能优化
const resdata = reactive({ data: null, stoptime: null, opentime: null, });
const getHaed = async (val) => { const data = { g: val, }; const res = await $API.game.index.head.get(data); if (res.code === 0) { const { nextGame } = res.data; resdata.data = nextGame; const timeA = new Date(nextGame.now).getTime(); const timeB = new Date(nextGame.stoptime).getTime(); const timeC = new Date(nextGame.opentime).getTime();
resdata.stoptime = (timeB - timeA) / 1000;
resdata.opentime = (timeC - timeA) / 1000;
daojishi();
clearInterval(timer.value); //清除定时器
timer.value = setInterval(() => {
daojishi();
}, 1000);
} }; // 代码优化如下: // 1. 将stoptime和opentime加入reactive对象中,方便在模板中使用 // 2. 解构res.data中的nextGame,简化代码 // 3. 将const res改成const { nextGame } = res.data,简化代码 // 4. 将获取时间戳的代码放入nextGame之后,简化代码 // 5. 将daojishi()函数提取出来,避免重复代码 // 6. 将定时器的清除和重设放在一起,简化代码
原文地址: https://www.cveoy.top/t/topic/lB9q 著作权归作者所有。请勿转载和采集!