vue의 상위 컴포넌트가 props를 통해 하위 컴포넌트로 데이터를 전달하지만 하위 컴포넌트가 데이터를 받지 못하는 문제 해결

문제: 부모 구성 요소는 마운트할 때 데이터를 얻기 위해 백엔드에 요청을 시작한 다음 얻은 데이터를 자식 구성 요소에 전달합니다.자식 구성 요소는 마운트할 때 데이터를 얻고 싶지만 가져올 수 없습니다.

코드 예:

//父组件
<template>
  <div>
    <HelloWorld :message="message"></HelloWorld>
  </div>
</template>

<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import {
    
     onMounted, ref } from "vue";
const message = ref("1");
onMounted(() => {
    
    
//模拟异步请求
   setTimeout(() => {
    
    
    message.value = "1312";
  }, 0);
});


</script>

<style scoped></style>
//子组件
<template>
  <div>{
    
    {
    
    message}}</div>
</template>

<script setup>
import {
    
     onMounted, defineProps } from "vue";
const props = defineProps(["message"]);
onMounted(() => {
    
    
  console.log("传递过来的数据", props.message);
});
</script>

<style scoped></style>

출력 결과: props.message는 부모 구성 요소 메시지의 초기 값인 비어 있지만 자식 구성 요소 데이터는 렌더링할 수 있습니다.
여기에 이미지 설명 삽입

원인 분석:

상위-하위 구성요소의 라이프 사이클 실행 순서는 다음과 같습니다.

데이터 렌더링 프로세스 로드

  • 부모 구성 요소 beforeCreate
  • 생성된 상위 구성 요소
  • 부모 컴포넌트 beforeMount
  • 만들기 전 하위 구성 요소
  • 생성된 하위 구성요소
  • 하위 구성요소 beforeMount
  • 탑재된 하위 구성 요소
  • 상위 구성요소가 마운트됨

렌더링 데이터 업데이트

  • 상위 구성 요소 beforeUpdate
  • 하위 구성 요소 beforeUpdate
  • 업데이트된 하위 구성 요소
  • 상위 구성 요소 업데이트됨

구성 요소 데이터 프로세스 파괴

  • Unmount 전에 상위 구성 요소
  • Unmount 전에 하위 구성 요소
  • 마운트 해제된 하위 구성요소
  • 마운트 해제된 상위 구성 요소

위의 로딩 데이터 렌더링 과정에서 자식 컴포넌트의 마운트된 컴포넌트가 부모 컴포넌트의 마운트된 컴포넌트보다 먼저 마운트되어 비동기 요청 후에 얻은 데이터를 얻을 수 없음을 알 수 있습니다.

해결책

방법 1: v-if를 사용하여 하위 구성 요소 렌더링 타이밍 제어

//父组件
<template>
  <div>
    <HelloWorld :message="message" v-if="isShow"></HelloWorld>
  </div>
</template>

<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import {
    
     onMounted, ref } from "vue";
const message = ref("1");
const isShow=ref(false);
onMounted(() => {
    
    
//模拟异步请求
   setTimeout(() => {
    
    
    message.value = "1312";
    isShow.value=true;//获取数据成功,再让子组件渲染
  }, 0);
});

</script>

<style scoped></style>

방법 2: 감시를 사용하여 상위 구성 요소가 전달한 데이터 모니터링

//子组件
<template>
  <div>{
    
    {
    
    message}}</div>
</template>

<script setup>
import {
    
     defineProps,watch} from "vue";
const props = defineProps(["message"]);
//监听传过来的数据
watch(()=>props.message,()=>{
    
    
 console.log("传递过来的数据", props.message);
})
</script>
<style scoped></style>

여기에 이미지 설명 삽입

추천

출처blog.csdn.net/CYL_2021/article/details/130323719