SoFunction
Updated on 2025-04-13

Vue uses dayjs encapsulation to achieve real-time refresh

1. Use mixins encapsulation in vue2

1.1 Packaging

// mixins/
import dayjs from 'dayjs'
export default {
  data() {
    return {
      currentTime: {
        timer: null,
        currentDay: ().day, // What day of the week        date: ().date, // Year, month, day        time: ().time, // hour, minute, second      },
    }
  },
  mounted() {
     = setInterval(() => {
      ()
    }, 1000)
  },
  methods: {
    formatTime(d = '', t = 'HH:mm:ss') {
      let days = ['day', 'one', 'two', 'three', 'Four', 'five', 'six']
      let date = dayjs(new Date()).format(d)
      let time = dayjs(new Date()).format(t)
      let day = `Week${days[dayjs().day()]}`
      return { date, time, day }
    },
    updateTime() {
       = ().day
       = ().date
       = ().time
    },
  },
  beforeDestroy() {
    clearInterval()
  },
}

1.2 Use in Components

<span>{{  }}</span>
<span>{{  }}</span>
<span>{{  }}</span>
<script>
import formatdate from '@/mixins/formatdate'
export default {
  mixins: [formatdate],
}
</script>

2. Use combination functions in vue3

2.1 Packaging

// 
import dayjs from 'dayjs'
import { onBeforeUnmount, onMounted, ref } from 'vue'
export function useTime() {
  // What day of the week  const currentDay = ref('')
  // Year, month, day  const date = ref('')
  // hour, minute, second  const time = ref('')
  // Get time  const updateTime = (d = '', t = 'HH:mm:ss') =&gt; {
    let days = ['day', 'one', 'two', 'three', 'Four', 'five', 'six']
     = dayjs(new Date()).format(d)
     = dayjs(new Date()).format(t)
     = `Week${days[dayjs().day()]}`
  }
  // Define the timer  let timer = null
  onMounted(() =&gt; {
    timer = setInterval(() =&gt; {
      updateTime()
    }, 1000)
  })
  onBeforeUnmount(() =&gt; clearInterval(timer))
  return { currentDay, date, time }
}

2.2 Use in components

<span>{{ currentDay }}</span>
<span>{{ date }}</span>
<span>{{ time }}</span>
<script setup>
import { useTime } from '@/utils/formatTime'
const { currentDay, date, time } = useTime()
</script>

This is the article about Vue using dayjs encapsulation to achieve real-time refresh time. For more related content on Vue dayjs time refresh, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!