Vue3 parent-child components pass value step on the pit point - the parent component obtains data asynchronously, and the child component receives the data but does not render

Vue parent-child component passing value stepping on the pit point - when the parent component obtains data asynchronously

在新手开发Vue项目时,很有可能会遇到这个问题,因此笔者在此做个简单记录,以供今后新手避坑

1. The parent component gets data asynchronously
注意:本文写法为vue3
Pseudocode:

const id=ref<number>(1)
const project=ref<string>()
//注意getProjecInfo为API接口
onMounted(async () => {
    
    
  project.value = await getProjecInfo(id.value)
  }

2. Subcomponents

//子组件通过
const props = defineProps<{
    
    
  getProjecInfo: string   //子组件接收
}>()
//解构赋值
const {
    
     getProjecInfo} = toRefs(props)

3. Solution (the key point is to use watch monitoring) when the value obtained asynchronously by the parent component is monitored and then used in the child component

watch(
  () => getProjecInfo.value,
  () => {
    
    
    console.log(getProjecInfo.value)
    //你的逻辑操作,比如将值赋值给你子组件的变量中
    .......
  },
  {
    
     deep: true }
)

The above solves this problem. The main reason is that the data obtained by the parent component is asynchronous. When it is passed to the child component, the child component is likely to have been rendered, so although the child component has received the value, the data has not been rendered. ! Use the watch to monitor the value and then perform the operation.

Guess you like

Origin blog.csdn.net/m0_46627407/article/details/125644589