vue異步更新

父組件的代碼如下,這個(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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容