项目文件夹

文件
2026-07-13 21:37:07 +08:00

3.3 KiB

name, description
name description
Provide / Inject 在组件树中传递数据,避免 Prop 逐级透传

Provide / Inject

从祖先组件向后代组件提供数据,避免 Prop 逐级透传。

基本用法

<!-- Provider.vue -->
<script setup lang="ts">
import { provide, ref } from 'vue'

const message = ref('hello')
provide('message', message)
</script>
<!-- DeepChild.vue任意层级深度 -->
<script setup lang="ts">
import { inject } from 'vue'

const message = inject('message')
</script>

使用 InjectionKey 进行类型标注

使用 InjectionKey 在提供方与注入方之间实现类型安全:

// keys.ts
import type { InjectionKey, Ref } from 'vue'

export const messageKey = Symbol() as InjectionKey<Ref<string>>
export const countKey = Symbol() as InjectionKey<number>
<!-- Provider.vue -->
<script setup lang="ts">
import { provide, ref } from 'vue'
import { messageKey } from './keys'

const message = ref('hello')
provide(messageKey, message)
</script>
<!-- Injector.vue -->
<script setup lang="ts">
import { inject } from 'vue'
import { messageKey } from './keys'

const message = inject(messageKey) // Ref<string> | undefined
</script>

默认值

// 简单默认值
const value = inject('message', 'default value')

// 工厂函数(用于创建成本较高的默认值)
const value = inject('key', () => new ExpensiveClass(), true)
//                                                       ^ 视为工厂函数

应用层 Provide

对所有组件可用:

// main.ts
import { createApp } from 'vue'

const app = createApp(App)
app.provide('globalConfig', { theme: 'dark' })

响应式 Provide/Inject

提供响应式值以实现自动更新:

<!-- Provider.vue -->
<script setup lang="ts">
import { provide, ref } from 'vue'

const count = ref(0)
provide('count', count)
</script>

注入的值保持与响应式系统的连接。

变更操作的最佳实践

将变更操作保留在提供方,对外暴露更新函数:

<!-- Provider.vue -->
<script setup lang="ts">
import { provide, ref, readonly } from 'vue'

const location = ref('North Pole')

function updateLocation(newLocation: string) {
  location.value = newLocation
}

provide('location', {
  location: readonly(location), // 防止直接修改
  updateLocation
})
</script>
<!-- Injector.vue -->
<script setup lang="ts">
import { inject } from 'vue'

const { location, updateLocation } = inject('location')!
</script>

<template>
  <button @click="updateLocation('South Pole')">
    {{ location }}
  </button>
</template>

使用 Symbol 键

推荐用于库和大型应用,以避免键名冲突:

// keys.ts
export const myKey = Symbol('myKey')

// provider 提供方
provide(myKey, value)

// injector 注入方
inject(myKey)

类型辅助

// 字符串键配合显式类型
const foo = inject<string>('foo')
//    ^? string | undefined

// 带默认值(移除 undefined
const foo = inject<string>('foo', 'default')
//    ^? string

// 强制非 undefined(确定已被提供时使用)
const foo = inject('foo') as string