欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue利用dayjs封裝實(shí)現(xiàn)時(shí)間實(shí)時(shí)刷新

 更新時(shí)間:2024年07月19日 08:54:49   作者:我是亮哥啊  
Day.js庫(kù)本身專注于簡(jiǎn)化JavaScript日期和時(shí)間的操作,它的API設(shè)計(jì)直觀,且功能強(qiáng)大,可以方便地格式化日期、添加或減去時(shí)間間隔、比較日期等,本文主要介紹了Vue利用dayjs封裝實(shí)現(xiàn)時(shí)間實(shí)時(shí)刷新,需要的朋友可以參考下

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, // 時(shí)分秒
      },
    }
  },
  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('')
  // 時(shí)分秒
  const time = ref('')
  // 獲取時(shí)間
  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()]}`
  }
  // 定義定時(shí)器
  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封裝實(shí)現(xiàn)時(shí)間實(shí)時(shí)刷新的文章就介紹到這了,更多相關(guān)Vue dayjs時(shí)間實(shí)時(shí)刷新內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論