vue中:在 子組件的created、mounted中獲取不到props中的值data(data為對象或者數據太大時取不到)


出現這種情況的原因 :因為父組件中的要就要傳遞的props屬性 是通過發生ajax請求回來的, 請求的這個過程是需要時間的,但是子組件的渲染要快於ajax請求過程,所以此時 created 、mounted這樣的只會執行一次的生命周期鈎子,已經執行了,但是props還沒有流進來(子組件),所以只能拿到默認值。

解決方法
①、watch處理
監聽 Data 的值,當它由空轉變時就會觸發,這時候就能取到了,拿到值后要做的處理方法也需要在 watch 里面執行

export default {
   props: ['Data'],
       data(){
           return {
               cData: []
           }
       },
       watch: {
           //正確給 Data 賦值的 方法
           Data: function(newVal,oldVal){
               this.cData = newVal;  //newVal即是chartData
               newVal && this.draw(); //newVal存在的話執行draw函數
           }
       },
       methods: {
           draw(){
               //執行其他邏輯
           }
       },
     
       mounted() {
           //在created、mounted這樣的生命周期, 給 this.Data賦值會失敗,錯誤賦值方法 
       }
}

②、加上 v-if 來判斷數據是否加載完成了,加載完了再渲染
A、flag默認值為false, 在父組件異步請求數據成功后flag變為true: <children v-if="flag" :list="list"></children>

          // 成功獲取數據后 flag設置成true
          homeResource.getConditionData().then((res) => {
              this.flag = true
              if (res.data.status === 0) {
                  console.log('條件', res.data.data)
                  this.list = res.data.data
              }
          })

B、 <children v-if="list.length" :list="list"></children>

③、setTimeout來做延遲,但這樣的方法不准確,應該視情況使用(不推薦)
************
類似問題 :vue在created異步請求數據,通過v-for渲染;在mounted中獲取不到數據和Dom的解決方案

鏈接:博主:MINO吖https://blog.csdn.net/qq_36157085/article/details/107962134?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allsobaiduend~default-1-107962134.nonecase&utm_term=created%20%E6%8B%BF%E5%88%B0%E6%95%B0%E6%8D%AE&spm=1000.2123.3001.4430

// template
 
<div
  class="scheme-tab"
  v-for="(tab,index) in tabs"
  :key="tab.id"
>
 
// JS
 
async created() {
  this.tabs = await this.fetchSolutionTypes();
  console.log(JSON.stringify(this.tabs)); // 有數據
},
mounted() {
  console.log(JSON.stringify(this.tabs)); // 沒有數據
  console.log(document.getElementsByClassName("scheme-tab")); // 沒有數據
}

目的:在created中異步獲取到數據后,在template中通過v-for渲染;然后在mounted中獲取到循環渲染的Dom節點。

但是在mounted中都獲取不到;

在mounted當中使用 this.$nextTick 也不好用;

使用setTimeout,設置延時可以,但是在網速不好的情況下還是有問題。所以不推薦;

解決方法
在watch當中監聽tabs數組,然后在watch函數中,通過nextTick獲取Dom節點;

watch: {
    tabs: function (val) {
      console.log(val); // 有數據
      this.$nextTick(() => {
        let curDom = document.getElementsByClassName("scheme-tab")[0]; // 有數據
      });
    }
},
async created() {
  this.tabs = await this.fetchSolutionTypes();
  console.log(JSON.stringify(this.tabs)); // 有數據
},
mounted() {
  // console.log(JSON.stringify(this.tabs));
  // console.log(document.getElementsByClassName("scheme-tab")); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM