Vue利用dayjs封裝實現(xiàn)時間實時刷新
更新時間:2024年07月19日 08:54:49 作者:我是亮哥啊
Day.js庫本身專注于簡化JavaScript日期和時間的操作,它的API設計直觀,且功能強大,可以方便地格式化日期、添加或減去時間間隔、比較日期等,本文主要介紹了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>到此這篇關于Vue利用dayjs封裝實現(xiàn)時間實時刷新的文章就介紹到這了,更多相關Vue dayjs時間實時刷新內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue項目拍照或上傳圖片并實現(xiàn)轉化為base64格式
這篇文章主要介紹了vue項目拍照或上傳圖片并實現(xiàn)轉化為base64格式方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

