Vue實現(xiàn)實時刷新時間的功能
前言
實現(xiàn)大屏的實時刷新時間的功能:在大屏中有時需要實現(xiàn)顯示日期和當前的時間的功能,且秒數(shù)需要實時刷新。
實現(xiàn)方法
要點:每隔一秒刷新一次。
<div class="date"> {{ time.date }} {{ time.week }} {{ time.time }} </div> <script setup> import { getTime } from '@/utils'; //獲取并刷新日期 const time = ref(''); const getDataTime = () => { time.value = getTime(); setTimeout(getDataTime, 1000); }; onMounted(() => { getDataTime(); }); </script> //getTime方法 export function getTime() { const nowDate = new Date() const date = nowDate.getFullYear() + '-' + _formatNum(nowDate.getMonth() + 1) + '-' + _formatNum(nowDate.getDate()) const time = _formatNum(nowDate.getHours()) + ':' + _formatNum(nowDate.getMinutes()) + ':' + _formatNum(nowDate.getSeconds()) let week = '' switch (nowDate.getDay()) { case 0: week = '星期天' break case 1: week = '星期一' break case 2: week = '星期二' break case 3: week = '星期三' break case 4: week = '星期四' break case 5: week = '星期五' break case 6: week = '星期六' break default: break } return { date, time, week } }
方法補充
vue獲取當前時間并實時刷新
1、在data中聲明變量
data() { return { nowDate: null, //存放年月日變量 nowTime: null, //存放時分秒變量 timer: "", //定義一個定時器的變量 currentTime: new Date(), // 獲取當前時間 } }
2、定義獲取時間的方法getTime,并在created()聲明周期里面調用,在實例創(chuàng)建前調用
created() { this.timer = setInterval(this.getTime, 1000); }
3、具體方法如下:
methods: { getTime(){ const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour= date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); const str = '' if(this.hour>12) { this.hour -= 12; this.str = " PM"; }else{ this.str = " AM"; } this.month=check(month); this.day=check(day); this.hour=check(hour); this.minute=check(minute); this.second=check(second); function check(i){ const num = (i<10)?("0"+i) : i; return num; } this.nowDate = year + "年" + this.month + "月" + this.day+"日"; this.nowTime = this.hour + ":" + this.minute + ":" + this.second + this.str; }, }
4、離開頁面使用beforeDestroy() 銷毀
beforeDestroy() { if (this.timer) { clearInterval(this.timer); // 在Vue實例銷毀前,清除定時器 } }
5、在頁面需要顯示的地方綁定{{ nowDate }},{{ nowTime }}即可
到此這篇關于Vue實現(xiàn)實時刷新時間的功能的文章就介紹到這了,更多相關Vue實時刷新時間內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
element-ui中this.$confirm提示文字中部分有顏色自定義方法
this.$confirm是一個Vue.js中的彈窗組件,其樣式可以通過CSS進行自定義,下面這篇文章主要給大家介紹了關于element-ui中this.$confirm提示文字中部分有顏色的自定義方法,需要的朋友可以參考下2024-02-02淺談Vue static 靜態(tài)資源路徑 和 style問題
這篇文章主要介紹了淺談Vue static 靜態(tài)資源路徑 和 style問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11element-ui和vue表單(對話框)驗證提示語(殘留)清除操作
這篇文章主要介紹了element-ui和vue表單(對話框)驗證提示語(殘留)清除操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09