Using dayjs to realize dynamic real-time update time based on Vue

LIYITONGXUEOriginalAugust 23, 2022
About 2 min...

Dayjs is a lightweight JavaScript library that handles time and date.

Chinese official documents:https://dayjs.gitee.io/zh-CN/open in new window

1 Install Dayjs Package

npm install dayjs

2 Import Dayjs

In main.jsfile,add import dayjs from 'dayjs' to import dayjs,as shown in the following figure:

image-20220817182445897

3 Add test.vue

create test.vueand add a test page in index.js,as shown in the following figure:

image-20220817183003203

add test.vue file below views/ package,The page code is as follows:

<template>
	{{currentTime}}
</template>
<script>
	import dayjs from 'dayjs';
	export default {
		data() {
			return {
				currentTime: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
			}
		},
		mounted() {
			let self = this;
			this.timer = setInterval(() => {
				self.currentTime = dayjs().format('YYYY年MM月DD日 HH:mm:ss')
			}, 1000)
		},
		beforeDestroy() {
			if (this.timer) {
				//组件销毁时,清除定时器
				clearInterval(this.timer)
			}
		},
	}
</script>
<style>
</style>

4 Test

Open this test address in the browser. Success:

image-20220817183223398

2022-08-17-18-35-37

Last update: 8/23/2022, 7:58:42 AM
Comments
Powered by Waline v2.6.2