vue获取并显示服务器时间

  • Post author:
  • Post category:vue


由于http响应头会带有服务器时间,所以就在响应拦截器中获取了服务器时间

import store from '@/store'
service.interceptors.response.use((response) => {
	if(response.headers['date']) {
		store.commit('common/setServiceTime', response.headers.date)
	}
})

common stroe

const state = {
	differTime: 0,
}

const mutations = {
	setServiceTime(state, date) {
		let localTime = new Date();
		let serveTime = new Date(date);
		state.differTime = localTime.valueOf() - serveTime.valueOf();
	},
}

mixin

export const mixinServerTime = {
	data() {
		return {
			currentServeTime: '',
		}
	},
  computed: {
		...mapState('common', {
			differTime: state => state.differTime,
		}),
	},
	created(){
		this.initTime();
	},
	methods: {
		initTime() {
			this.getTime();
			this.timer = setInterval(() => {
				this.getTime();
			}, 1000)
		},
		getTime() {
			let now = new Date();
			console.log(new Date(now.valueOf() - this.differTime));
			
			this.currentServeTime = new Date(now.valueOf() - this.differTime).format()
		},
	}
}

currentServeTime即为服务器时间。

关于定时器,为了时间更精确,可以设置500ms更新



版权声明:本文为qq_28259083原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。