* provide 和 inject 提供依賴注入,功能類似 vue2.x 的 provide/inject。
* 實現跨層級組件間通信。祖組件可以直接與子孫組件通信,不再需要通過父組件。

**1. 祖組件`src/components/LearnProvideInjectParent.vue`**
```html
<template>
<h1>祖組件</h1>
<button @click="update">更新</button>
<h3>{{ num }}</h3>
<hr />
<!-- 2. 祖組件中引入父組件 -->
<LearnProvideInjectParent></LearnProvideInjectParent>
</template>
<script lang="ts">
import { defineComponent, provide, ref } from 'vue'
import LearnProvideInjectParent from './LearnProvideInjectParent.vue'
export default defineComponent({
name: 'LearnProvideInjectGrand',
setup() {
const num = ref(0)
const update = () => {
num.value++
}
//1. 調用provide提供一個num屬性
provide('num', num)
return {
num,
update,
}
},
components: {
LearnProvideInjectParent,
},
})
</script>
```
**2. 父組件`src/components/LearnProvideInjectGrandSon.vue`**
```html
<template>
<h1>父組件</h1>
<hr />
<!-- 1. 父組件中引入子孫組件 -->
<LearnProvideInjectGrandSon></LearnProvideInjectGrandSon>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LearnProvideInjectGrandSon from './LearnProvideInjectGrandSon.vue'
export default defineComponent({
name: 'LearnProvideInjectParent',
setup() {
console.log('')
},
components: {
LearnProvideInjectGrandSon,
},
})
</script>
```
**3. 子孫組件`src/components/LearnProvideInjectGrandSon.vue`**
```html
<template>
<h1>子孫組件</h1>
<h3>{{ num }}</h3>
</template>
<script lang="ts">
import { defineComponent, inject } from 'vue'
export default defineComponent({
name: 'LearnProvideInjectGrandSon',
setup() {
//1. 調用inject獲取祖組件中的num屬性值
const num = inject('num')
return {
num,
}
},
})
</script>
```
**4. 效果**
可見,祖組件可以跨過父組件直接給子孫組件傳遞數據。

- nodejs
- 同時安裝多個node版本
- Vue3
- 創建Vue3項目
- 使用 vue-cli 創建
- 使用 vite 創建
- 常用的Composition API
- setup
- ref
- reactive
- 響應數據原理
- setup細節
- reactive與ref細節
- 計算屬性與監視
- 生命周期函數
- toRefs
- 其它的Composition API
- shallowReactive與shallowRef
- readonly與shallowReadonly
- toRaw與markRaw
- toRef
- customRef
- provide與inject
- 響應式數據的判斷
- 組件
- Fragment片斷
- Teleport瞬移
- Suspense
- ES6
- Promise對象
- Promise作用
- 狀態與過程
- 基本使用
- 常用API
- async與await
- Axios