在vue中利用dayjs封装,实现时间实时刷新

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中利用组合式函数

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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值