网络编程
位置:首页>> 网络编程>> JavaScript>> vue 解决异步数据更新问题

vue 解决异步数据更新问题

作者:潇蓝诺依  发布时间:2024-04-30 10:45:28 

标签:vue,异步,数据,更新

问题

记录一下出现的问题, 数据翻倍

这是复现问题的代码


data() {
 return {
  space: "",
  allresult: []
 };
},
methods: {
 getmessage() {
  this.allresult = [];
  axios
   .get(
    "https://gist.githubusercontent.com/xiaolannuoyi/9b0defe4959e71fa97e6096cc4f82ba4/raw/4be939123d488cee7ecefc055fb5ecb2ed8d5c8d/test"
   )
   .then(data => {
    console.log(data);
    let result = data.data;
    for (let i = 0; i < result.length; i++) {
     //原因在于这里的this.Allresult
     this.allresult.push({
      id: result[i].id,
      name: result[i].name,
      age: result[i].age
     });

}
     console.log('此时的this.allresult',this.allresult);
   });
 }
},
watch: {
 space() {
  console.log("watch");
  this.getmessage();
 }
},
mounted() {
 this.space = "123";
 console.log("mounted");
 this.getmessage();
}

结果

vue 解决异步数据更新问题

此时你可以看到第二次的数据时 是 第一次的 2倍

原因

mounted 和 watch 都执行 getmessage 方法,虽然方法之前 对数据进行了清空,但是 异步请求执行的慢,

所以两次调用getmessage相当于 this.allresult = []; this.allresult = []; axios...;axios....: 这个顺序

所以才会出现上述现象

解决

1.修改this.allresult = []的位置

vue 解决异步数据更新问题

2.新建一个临时空数组

vue 解决异步数据更新问题

来源:https://blog.csdn.net/qq_31126175/article/details/86512328

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com