Vue 3 中的 provide 和 inject 是一對強大的 API,使得在父子組件之間進行數(shù)據(jù)傳遞變得更加簡單。通過 provide 在父組件中提供數(shù)據(jù)悔常,并使用 inject 在子組件中注入這些數(shù)據(jù),我們可以輕松地實現(xiàn)跨組件
什么是 provide 和 inject?
provide 和 inject 是 Vue 3 中提供的一對用于父子組件之間進行數(shù)據(jù)傳遞的 API轧钓。通過 provide,父組件可以提供數(shù)據(jù)锐膜;而 inject 則允許子組件在任何地方注入這些數(shù)據(jù)毕箍。
這種方式使得數(shù)據(jù)在組件樹中的傳遞變得更加簡單和直接,無需通過繁瑣的 prop 屬性傳遞道盏。
使用 provide 提供數(shù)據(jù)
在父組件中而柑,我們可以使用 provide 函數(shù)來提供數(shù)據(jù)給子組件。下面是一個示例:
//ParentComponent.vue
<script lang="ts" setup>
import child from "./components/child.vue"
import { ref, provide } from "vue"
const loading = ref<Boolean>(true)
// 使用 provide 提供數(shù)據(jù)給子組件
provide("message", loading)
</script>
<template>
<div class="app-container">
<child />
</div>
</template>
<style lang="scss" scoped></style>
使用 inject 注入數(shù)據(jù)
在子組件中荷逞,我們可以使用 inject 函數(shù)來注入父組件提供的數(shù)據(jù)
//ChildComponent.vue
<script lang="ts" setup>
import { inject } from "vue"
const loading = inject("message")
</script>
<template>
<el-button @click="loading = !loading">關閉</el-button>
<div class="app-container" v-loading="loading">child</div>
</template>
<style lang="scss" scoped></style>
用 inject 來注入父組件提供的數(shù)據(jù)媒咳。我們使用 'loading' 作為鍵來獲取父組件提供的數(shù)據(jù),并將其賦值給 loading 變量种远。
現(xiàn)在涩澡,子組件可以在任何地方直接使用 loading,而不需要通過繁瑣的 prop 屬性傳遞數(shù)據(jù)院促。
注意事項和使用場景
在使用 provide 和 inject 時筏养,需要注意以下幾點:
provide 和 inject 需要在父組件和子組件之間存在直接或間接的關系斧抱。也就是說,它們只能在共同的祖先組件中使用渐溶。
provide 和 inject 并不會觸發(fā)響應式更新辉浦。如果提供的數(shù)據(jù)是響應式的,子組件無法自動更新茎辐。如果需要響應式的數(shù)據(jù)傳遞宪郊,請使用 reactive 或 ref 來包裝提供的數(shù)據(jù)。
使用 provide 提供的數(shù)據(jù)是全局可訪問的拖陆,因此請注意不要與其他組件提供的相同鍵名發(fā)生沖突弛槐。
這對 API 在一些場景下非常有用,例如在多層級嵌套的組件樹中傳遞主題依啰、用戶身份信息等全局數(shù)據(jù)乎串,或者在父組件提供配置選項給所有子組件使用等。