我是想做一个网站建站时间的检测显示 , 所以我想使用这个函数定时循环执行一段代码
使用起来很简单:
在mounted钩子函数中使用就可以
mounted() {
let that = this
this.timer = setInterval(that.createTime(), 1000);
},
来看看我的
<script>
export default {
name: "Footer",
data() {
return {
timer: '',
dum: 0,
hnum: 0,
mnum: 0,
snum: 0
};
},
created() {
},
mounted() {
this.timer = setInterval(function () {
that.createTime()
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
},
methods: {
createTime() {
// 页脚建站时间计算脚本
let now = new Date();
let grt = new Date("04/01/2020 00:00:00");//在此处修改你的建站时间,格式:月/日/年 时:分:秒
now.setTime(now.getTime() + 250);
let days = (now - grt) / 1000 / 60 / 60 / 24;
this.dnum = Math.floor(days);
let hours = (now - grt) / 1000 / 60 / 60 - (24 * this.dnum);
this.hnum = Math.floor(hours);
if (String(this.hnum).length == 1) {
this.hnum = "0" + this.hnum;
}
let minutes = (now - grt) / 1000 / 60 - (24 * 60 * this.dnum) - (60 * this.hnum);
this.mnum = Math.floor(minutes);
if (String(this.mnum).length == 1) {
this.mnum = "0" + this.mnum;
}
let seconds = (now - grt) / 1000 - (24 * 60 * 60 * this.dnum) - (60 * 60 * this.hnum) - (60 * this.mnum);
this.snum = Math.round(seconds);
if (String(this.snum).length == 1) {
this.snum = "0" + this.snum;
}
console.log("----------------------------->" , this.dnum)
}
}
}
</script>
这样有一个致命的错误
在setInterval函数中调用总说createTime不是一个函数
那么我们怎么办呢?
解决方式
首先我们先说为什么会报错说createTime不是一个方法呢
原因其实很简单
就是在setInterval这个函数中this的指向不再是vue , 这里面的this指向是windows
所以解决方式就是我们定义一个变量 , 将this赋值给这个变量 , 在setInterval函数中用这个变量去指向调用函数
<script>
export default {
name: "Footer",
data() {
return {
timer: '',
dum: 0,
hnum: 0,
mnum: 0,
snum: 0
};
},
created() {
},
mounted() {
let that = this
this.timer = setInterval(function () {
that.createTime()
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
},
methods: {
createTime() {
// 页脚建站时间计算脚本
let now = new Date();
let grt = new Date("04/01/2020 00:00:00");//在此处修改你的建站时间,格式:月/日/年 时:分:秒
now.setTime(now.getTime() + 250);
let days = (now - grt) / 1000 / 60 / 60 / 24;
this.dnum = Math.floor(days);
let hours = (now - grt) / 1000 / 60 / 60 - (24 * this.dnum);
this.hnum = Math.floor(hours);
if (String(this.hnum).length == 1) {
this.hnum = "0" + this.hnum;
}
let minutes = (now - grt) / 1000 / 60 - (24 * 60 * this.dnum) - (60 * this.hnum);
this.mnum = Math.floor(minutes);
if (String(this.mnum).length == 1) {
this.mnum = "0" + this.mnum;
}
let seconds = (now - grt) / 1000 - (24 * 60 * 60 * this.dnum) - (60 * 60 * this.hnum) - (60 * this.mnum);
this.snum = Math.round(seconds);
if (String(this.snum).length == 1) {
this.snum = "0" + this.snum;
}
console.log("----------------------------->" , this.dnum)
}
}
}
</script>