Clear the execution order of the parent-child component life cycle

Project scenario:

提示:这里简述项目相关背景:


Problem Description

提示:这里描述项目中遇到的问题:
The data returned by the ajax request is stored in data and passed to the subcomponent. The request returns data, but the subcomponent created print is empty

                     //父组件代码页
<template>
  <comDialog :dataInfor="dataInfor" ></comDialog>
</template>
<script>
import comDialog from "../components/dialog.vue";
export default {
    
    
  components: {
    
    
    comDialog
  },
  data() {
    
    
    return {
    
    
      dataInfor: [],
    };
  },
  created() {
    
    
    this.a()
  },
  methods: {
    
    
    a(){
    
    
    //模拟异步请求
      setTimeout(() => {
    
    
        this.dataInfor=[ {
    
     name: "陈梦圆", age: "18", sex: "女",id:1 }]
      },500)
    }
}
</script>


//子组件代码页
<script>
export default {
    
    
  props: {
    
    
    dataInfor: {
    
    },
  },
  data() {
    
    
    return {
    
    
    };
  },
  created() {
    
    
    console.log(this.dataInfor,"aaaaa");//结果为空
   },
  }
  </script>

Cause Analysis:

Because the request is asynchronous, the value passed to the child component is the initial value. The initial value of the variable in the created print is empty. On the essence!
【Execution sequence of parent-child component life cycle
parent beforeCreate-> parent create-> child beforeCreate-> child created-> child mounted-> parent mounted-> parent asynchronous request, so it will be clear】
Add again! ! ! ! ! ! ! ! ! ! !
In the order of asynchronous requests and DOM mounting?
Answer: I am mounted.
I am nextTick in mounted.
I am requesting asynchronously.
I'm nextTick asynchronous request.
The dom is mounted first, and then executed asynchronously.

solution:

1. This value can be monitored in subcomponents. This was mentioned in the previous article
2. Add v-if to the component tag and add a switch. After the request returns data, the switch is true. When the assigned data is not empty and the switch is true, then render the child components.

Guess you like

Origin blog.csdn.net/qq_48850466/article/details/124650646