今天在使用SetInterval的时候遇到了这样一个问题:就是setInterval中调用后端接口,直到满足条件就跳转页面。
跳转页面代码:
this.$router.push({name:"Start"})
但是一直报这个错:

错因:这个this是window的,而不是Vue的,所以我们需要在SetInterval外面先用一个变量存起来,然后再使用
window的this:

vue的this:

var that=this;
const timer=setInterval(function(){
axios.get('/gameApi/api/result').then(res=>{
if(res.data.data.state==2){
if(type==="pepper"){
score=3;
}else if(type==="apple"){
score=2;
}else if(type==="orange"){
score=1;
}
// Message({
// message: res.data.msg,
// type: 'success',
// duration: 3 * 1000
// });
//把分数加起来
let newScore=config.score+score;
config.setScore(newScore);
//销毁interval
clearInterval(timer);
console.log(this);
// 跳转到start页面
that.$router.push({name:"Start"})
}
})
},1000)
倒计时实现(手机短息验证码)
页面:
<el-button class="identify" @click="getAuthCode">{{data.status?(data.second+'s'):'获取验证码'}}</el-button>
data:
data: {
second: 60,
status: false
}
JS:
var vm=this;
var data=vm.data;
if(data.status) return;
data.status=true;
var time=setInterval(()=>{
var second = data.second;
second--;
data.second = second;
if (second == 0) {
clearInterval(time);
data.second = 60;
data.status = false;
}
},1000);
小白还需要成长,慢慢积累,总会有收获的。不积跬步无以至千里,不积小流无以成江海。
本文探讨了在Vue项目中使用setInterval调用后端接口并进行页面跳转时遇到的问题,详细介绍了如何正确处理this上下文,确保定时器内Vue实例方法的正确执行。
800

被折叠的 条评论
为什么被折叠?



