前端js實(shí)現(xiàn)一個時間實(shí)時更新效果
按秒刷新砰逻,實(shí)現(xiàn)效果如圖:
簡單原理就是:
封裝一個時間格式的方法髓梅,加一個定時器寡喝,每秒去刷新一次拯田,模擬成為時間更新效果
1. 封裝公共方法
export function timeNow() {
let vWeek, vWeek_s, year, month, day, hours, minutes, seconds;
vWeek = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hours = date.getHours();
hours = hours > 9 ? hours : "0" + hours;
minutes = date.getMinutes();
minutes = minutes > 9 ? minutes : "0" + minutes;
seconds = date.getSeconds();
seconds = seconds > 9 ? seconds : "0" + seconds;
vWeek_s = date.getDay();
let time = year + "年" + month + "月" + day + "日" + "\t" + hours + ":" + minutes + ":" + seconds + "\t" + vWeek[vWeek_s];
return time
}
可以根據(jù)需求更改展現(xiàn)格式
2. 使用
引入:
import { timeNow } from "../../utils/getMaininfo";
從頁面加載起,開始執(zhí)行:
getAll() {
this.tiemEq = setInterval(() => {
/* 時間 */
this.nowTime = timeNow();
}, 1000);
}
注:這里給定時器生成定義垃瞧,以便后續(xù)銷毀
3. 銷毀
由于定時器的特殊性蔫劣,在關(guān)閉頁面時,及時銷毀个从,避免造成資源浪費(fèi)甚至內(nèi)存溢出
// vue生命周期
beforeDestroy() {
/* 關(guān)閉頁面銷毀所有定時器 */
clearInterval(this.tiemEq);
}