父組件的代碼如下,這個(gè)組件有個(gè)userId,通過(guò)props傳給了子組件UserInfo,同時(shí)這個(gè)子組件暴露一個(gè)方法getUserInfo(),在父組件中去更改這個(gè)userId,更新完后馬上就調(diào)了這個(gè)getUserInfo方法,那么這個(gè)子組件中的props.userId是獲取到什么值
<template>
<div class="m-100">
<el-buttom class="mb-20" type="primary" @click="updateUser">更新用戶</el-buttom>
<UserInfo ref="userRef" :userId="userId"></UserInfo>
</div>
</template>
<script setup lang="ts">
import { UserInfo } from '.UserInfo.vue';
import { type ComponentInstance, ref } from 'vue';
const userId = ref(1);
const userRef = ref<ComponentInstance<typeof UserInfo>>();
function updateUser() {
userId.value = 2;
userRef.value?.getUserInfo();
}
</script>
<style scoped>
</style>
子組件userInfo的代碼如下:
<template>
<div>
userId {{userId}}
</div>
</template>
<script setup lang="ts">
const props = defineProps(['userId'])
defineExpose({
getUserInfo() {
//發(fā)送請(qǐng)求獲取最新的數(shù)據(jù)
console.log('獲取用戶信息', props.userId)
}
})
</script>
<style scoped>
</style>

image.png
視圖已經(jīng)更新了,但是子組件中打印出來(lái)還是原來(lái)的值,為什么會(huì)出現(xiàn)這中情況呢?
因?yàn)関ue的更新是異步的

image.png
當(dāng)點(diǎn)擊按鈕觸發(fā)頁(yè)面更新,但是這個(gè)頁(yè)面更新是異步的,在父組件修改了userId后,props實(shí)際上還是沒(méi)有更新

image.png
所以要想拿到最新的數(shù)據(jù),可以在父組件中調(diào)用nextTick
function updateUser() {
userId.value = 2;
nextTick(() => {
userRef.value?.getUserInfo();
});
}
或者在子組件中用watch監(jiān)聽(tīng)props
<template>
<div>
userId: {{ userId }}
</div>
</template>
<script setup lang="ts">
import { defineProps, watch } from "vue";
const props = defineProps(['userId'])
watch(() => props.userId, (newVal) => {
console.log('userId', newVal)
})
// defineExpose({
// getUserInfo() {
// console.log('獲取用戶信息', props.userId)
// }
// })
</script>