Vue利用dayjs封裝實現(xiàn)時間實時刷新
更新時間:2024年07月19日 08:54:49 作者:我是亮哥啊
Day.js庫本身專注于簡化JavaScript日期和時間的操作,它的API設(shè)計直觀,且功能強(qiáng)大,可以方便地格式化日期、添加或減去時間間隔、比較日期等,本文主要介紹了Vue利用dayjs封裝實現(xiàn)時間實時刷新,需要的朋友可以參考下
1、vue2中使用mixins封裝
1.1 封裝
// mixins/formatdate.js import dayjs from 'dayjs' export default { data() { return { currentTime: { timer: null, currentDay: this.formatTime().day, // 星期幾 date: this.formatTime().date, // 年月日 time: this.formatTime().time, // 時分秒 }, } }, mounted() { this.timer = setInterval(() => { this.updateTime() }, 1000) }, methods: { formatTime(d = 'YYYY.MM.DD', t = 'HH:mm:ss') { let days = ['日', '一', '二', '三', '四', '五', '六'] let date = dayjs(new Date()).format(d) let time = dayjs(new Date()).format(t) let day = `星期${days[dayjs().day()]}` return { date, time, day } }, updateTime() { this.currentTime.currentDay = this.formatTime().day this.currentTime.date = this.formatTime().date this.currentTime.time = this.formatTime().time }, }, beforeDestroy() { clearInterval(this.timer) }, }
1.2 在組件中使用
<span>{{ currentTime.date }}</span> <span>{{ currentTime.currentDay }}</span> <span>{{ currentTime.time }}</span> <script> import formatdate from '@/mixins/formatdate' export default { mixins: [formatdate], } </script>
2、vue3中利用組合式函數(shù)
2.1 封裝
// formatTime.js import dayjs from 'dayjs' import { onBeforeUnmount, onMounted, ref } from 'vue' export function useTime() { // 星期幾 const currentDay = ref('') // 年月日 const date = ref('') // 時分秒 const time = ref('') // 獲取時間 const updateTime = (d = 'YYYY.MM.DD', t = 'HH:mm:ss') => { let days = ['日', '一', '二', '三', '四', '五', '六'] date.value = dayjs(new Date()).format(d) time.value = dayjs(new Date()).format(t) currentDay.value = `星期${days[dayjs().day()]}` } // 定義定時器 let timer = null onMounted(() => { timer = setInterval(() => { updateTime() }, 1000) }) onBeforeUnmount(() => clearInterval(timer)) return { currentDay, date, time } }
2.2 在組件中使用
<span>{{ currentDay }}</span> <span>{{ date }}</span> <span>{{ time }}</span> <script setup> import { useTime } from '@/utils/formatTime' const { currentDay, date, time } = useTime() </script>
到此這篇關(guān)于Vue利用dayjs封裝實現(xiàn)時間實時刷新的文章就介紹到這了,更多相關(guān)Vue dayjs時間實時刷新內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用crypto-js對文件上傳下載進(jìn)行加密處理
這篇文章主要介紹了如何使用crypto-js對文件上傳下載進(jìn)行加密處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05詳解Vue學(xué)習(xí)筆記進(jìn)階篇之列表過渡及其他
本篇文章主要介紹了詳解Vue學(xué)習(xí)筆記進(jìn)階篇之列表過渡及其他,具有一定的參考價值,有興趣的可以了解一下2017-07-07vite build vue3項目配置開啟sourcemap方式
這篇文章主要介紹了vite build vue3項目配置開啟sourcemap方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06Vue使用html2canvas實現(xiàn)截取圖片并保存
html2canvas是一個JavaScript庫,它可以將HTML元素轉(zhuǎn)換為Canvas元素本文將介紹一下Vue如何使用html2canvas實現(xiàn)截取圖片并保存功能,需要的可以參考下2023-12-12如何在vue3中使用滑塊檢驗vue-puzzle-verification
這篇文章主要介紹了在vue3中使用滑塊檢驗vue-puzzle-verification的相關(guān)資料,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11