vue3父子組件和provide、inject數(shù)據(jù)異步問題及解決
更新時間:2026年06月30日 10:46:10 作者:西門飄雪01
這段文章主要討論了Vue3中父組件通過異步獲取后組件數(shù)據(jù)不實時響應的問題,并提出使用watch監(jiān)聽解決方法,同時簡要介紹了Vue3中provide和inject實現(xiàn)響應式傳值的方法
一、vue3父組件數(shù)據(jù)是請求后端獲取的數(shù)據(jù)時
就會出現(xiàn)數(shù)據(jù)不實時響應。因為在獲取數(shù)據(jù)之前子組件已經(jīng)加載,渲染完成了。所以這個時候接受父組件的異步數(shù)據(jù)不會實時更新。
要解決這個問題就得用到watch監(jiān)聽函數(shù)了,利用watch監(jiān)聽父組件傳過來的值,當值發(fā)生變化時,執(zhí)行相應的操作。
父組件:
<script setup>
let result=ref()
axios({
method: method,
url: url,
data:data,
headers: {
'Content-Type':'application/json'
}
}).then((res)=>{
//獲取到數(shù)據(jù)之后,賦值給定義好的變量。
result.value=res
})
</script>子組件:
//子組件利用defineProps來接受父組件傳過來的值
<script setup>
import {defineProps,toRefs,watch} from 'vue'
const props=defineProps({
result:Object//父組件傳過來的值
})
let {result}=toRefs(props)//解構props拿到result
//然后watch監(jiān)聽
watch(()=>props.result,(newval,oldval)=>{
console.log(newval)
console.log(oldval)
//newval就是最新更新的result。
})
</script>二、vue3.0中provide和inject實現(xiàn)響應式傳值
父組件中:
<template>
<div>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';
const asyncData = ref('');
// 模擬一個異步獲取數(shù)據(jù)的函數(shù)
const fetchAsyncData = async () => {
asyncData.value = await Promise.resolve('異步數(shù)據(jù)');
};
// 在setup中調(diào)用異步函數(shù)
fetchAsyncData();
// 使用provide提供異步數(shù)據(jù)
provide('asyncData', asyncData);
</script>子組件中:
<template>
<div>
異步數(shù)據(jù): {{ asyncData }}
</div>
</template>
<script setup>
import { inject, ref, watch } from 'vue';
// 使用inject注入異步數(shù)據(jù)
const asyncData = inject('asyncData');
// 如果需要響應式更新,可以使用watch來監(jiān)聽數(shù)據(jù)變化
watch(asyncData, (newValue) => {
console.log('異步數(shù)據(jù)更新了:', newValue);
});
</script>總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
淺談Vue2.4.0 $attrs與inheritAttrs的具體使用
這篇文章主要介紹了淺談Vue2.4.0 $attrs與inheritAttrs的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03

