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")); 
原文地址:https://www.cnblogs.com/wmt-kilig/p/14015880.html