1. 程式人生 > 實用技巧 >vue中:在 子元件的created、mounted中獲取不到props中的值data(data為物件或者資料太大時取不到)

vue中:在 子元件的created、mounted中獲取不到props中的值data(data為物件或者資料太大時取不到)

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

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

export default {
   props: ['Data'],
       data(){
           return {
               cData: []
           }
       },
       watch: {
           //正確給 Data 賦值的 方法
           chartData: 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-2all

sobaiduend~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"));