vue解決異步數(shù)據(jù)更新問(wèn)題

問(wèn)題

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、小程序定制開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了雙河免費(fèi)建站歡迎大家使用!

記錄一下出現(xiàn)的問(wèn)題, 數(shù)據(jù)翻倍

這是復(fù)現(xiàn)問(wèn)題的代碼

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('此時(shí)的this.allresult',this.allresult);
    });
  }
 },
 watch: {
  space() {
   console.log("watch");
   this.getmessage();
  }
 },
 mounted() {
  this.space = "123";
  console.log("mounted");
  this.getmessage();
 }

結(jié)果

vue 解決異步數(shù)據(jù)更新問(wèn)題

此時(shí)你可以看到第二次的數(shù)據(jù)時(shí) 是 第一次的 2倍

原因

mounted 和 watch 都執(zhí)行 getmessage 方法,雖然方法之前 對(duì)數(shù)據(jù)進(jìn)行了清空,但是 異步請(qǐng)求執(zhí)行的慢,

所以兩次調(diào)用getmessage相當(dāng)于 this.allresult = []; this.allresult = []; axios...;axios....: 這個(gè)順序

所以才會(huì)出現(xiàn)上述現(xiàn)象

解決

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

vue 解決異步數(shù)據(jù)更新問(wèn)題

2.新建一個(gè)臨時(shí)空數(shù)組

vue 解決異步數(shù)據(jù)更新問(wèn)題

以上這篇vue 解決異步數(shù)據(jù)更新問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前標(biāo)題:vue解決異步數(shù)據(jù)更新問(wèn)題
URL標(biāo)題:http://muchs.cn/article10/ighsdo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、用戶體驗(yàn)、虛擬主機(jī)、品牌網(wǎng)站制作、網(wǎng)站導(dǎo)航、關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司