今天在项目中有一个功能是要求显示北京的实时时间,后台的接口用的淘宝获取当前时间API
url:http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp
返回来的是一个时间戳
{
"api": "mtop.common.getTimestamp",
"v": "*",
"ret": ["SUCCESS::接口调用成功"],
"data": {
"t": "1592663852058"
}
}
实现思路参考了 https://blog.csdn.net/qq_44410862/article/details/121641580 可以自己看看实现的思路
我这里实现的代码
gettime() {
axios.post("/tapi").then(res => {
this.bgTime = parseTime(res.data.data.t)
if(this.bgTime){
this.getTimeBack(res.data.data.t)
}
});
},
getTimeBack(date) {
setInterval(() => {
date = parseInt(date) + 1000
this.bgTime = parseTime(date)
}, 1000);
},
2===========================================================
不从后台获取时间‘
实现代码
<div id="app">{{date}}</div>
<script>
export default {
data() {
return {
date: new Date()
};
},
mounted() {
let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
this.timer = setInterval(() => {
_this.date = new Date(); // 修改数据date
}, 1000)
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
}
}
};
</script>