4.8 Vue 3: provide / inject 详解
Vue 3: provide
/ inject
详解
1. 基本用法
在 Vue 3 的 Composition API (<script setup>
) 中,provide
和 inject
是独立的函数。
<!-- 父组件 (或祖先组件) -->
<script setup>
import { provide, ref } from 'vue'// 定义要提供的数据
const theme = ref('dark')
const userName = ref('Alice')// 使用 provide 函数提供数据
// 第一个参数是注入的 key (可以是字符串或 Symbol)
// 第二个参数是要提供的值
provide('theme', theme)
provide('userName', userName)// 也可以提供方法
function updateTheme(newTheme) {theme.value = newTheme
}
provide('updateTheme', updateTheme)
</script><template><div><h1>Parent Component (Theme: {{ theme }})</h1><ChildComponent /></div>
</template>
<!-- 子组件 (或任意后代组件) -->
<script setup>
import { inject, ref } from 'vue'// 使用 inject 函数注入数据
// 第一个参数是提供的 key
// 第二个参数 (可选) 是默认值
const theme = inject('theme', 'light') // 如果没找到,用 'light'
const userName = inject('userName')
const updateTheme = inject('updateTheme')// 注意:注入的 ref 是响应式的!可以直接使用
</script><template><div :class="theme"><h2>Child Component</h2><p>User: {{ userName }}</p><button @click="updateTheme('light')">Set Light Theme</button><button @click="updateTheme('dark')">Set Dark Theme</button></div>
</template>
2. 关键特性 (Vue 3)
-
响应式是默认的且更直观:
- 如果你
provide
一个ref
或reactive
对象,那么在inject
的地方,这个值是响应式的。 - 修改
provide
端的响应式数据,所有 <
- 如果你