vue 解决异步数据更新问题

发布时间:2020-10-16 14:04:18 作者:潇蓝诺依
来源:脚本之家 阅读:143

问题

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

这是复现问题的代码

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 解决异步数据更新问题

以上这篇vue 解决异步数据更新问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. 详解Vue 数据更新了但页面没有更新的解决方案
  2. 解决vue keep-alive 数据更新的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue 异步 数据

上一篇:如何将html网页放置到虚拟主机

下一篇:使用虚拟主机如何格式化

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》