当前位置: 首页 > news >正文

Vue3 + TypeScript中provide和inject的用法示例

基础写法(类型安全)

typescript

// parent.component.vue
import { provide, ref } from 'vue'
import type { InjectionKey } from 'vue'// 1. 定义类型化的 InjectionKey
const COUNTER_KEY = Symbol() as InjectionKey<number>
const USER_KEY = Symbol() as InjectionKey<{ name: string }>// 在 setup 中使用
setup() {const counter = ref(0)provide(COUNTER_KEY, counter) // 提供响应式数据const user = { name: 'John' }provide(USER_KEY, user) // 提供静态对象return { counter }
}

typescript

// child.component.vue
import { inject } from 'vue'
import type { InjectionKey } from 'vue'// 复用相同的 key
const COUNTER_KEY = Symbol() as InjectionKey<number>
const USER_KEY = Symbol() as InjectionKey<{ name: string }>setup() {// 2. 安全注入(带默认值)const counter = inject(COUNTER_KEY, ref(0)) // 响应式数据const user = inject(USER_KEY, { name: 'Guest' }) // 静态数据// 3. 强制注入(当确定父级已提供时)const forcedCounter = inject(COUNTER_KEY)!return { counter, user }
}

<script setup> 语法糖写法

vue

<!-- Parent.vue -->
<script setup lang="ts">
import { provide, ref } from 'vue'// 定义 key
const messageKey = Symbol() as InjectionKey<string>const message = ref('Hello from parent')
provide(messageKey, message)
</script>

vue

<!-- Child.vue -->
<script setup lang="ts">
import { inject } from 'vue'const messageKey = Symbol() as InjectionKey<string>// 注入 + 类型声明
const message = inject(messageKey, 'default message')// 处理可能 undefined 的情况
const safeMessage = inject(messageKey) ?? 'fallback value'
</script>

响应式对象注入

typescript

// types.ts
export interface User {id: numbername: string
}export const UserKey = Symbol() as InjectionKey<User>

vue

<!-- Parent.vue -->
<script setup lang="ts">
import { provide, reactive } from 'vue'
import { UserKey } from './types'const user = reactive({id: 1,name: 'Alice'
})provide(UserKey, user)
</script>

vue

<!-- Child.vue -->
<script setup lang="ts">
import { inject } from 'vue'
import { UserKey } from './types'const user = inject(UserKey)// 使用时需要处理可能 undefined 的情况
if (user) {console.log(user.name) // 类型安全
}
</script>

最佳实践提醒:

  1. 使用 InjectionKey:确保类型安全

  2. 默认值处理inject(key, defaultValue)

  3. 响应式数据:建议使用 ref/reactive 保持响应性

  4. 代码组织:推荐将 keys 集中管理在单独文件中

  5. 安全判断:当不确定是否已提供时,使用可选链操作符 ?.

typescript

// 推荐的文件结构
// src/provides/keys.ts
import type { InjectionKey } from 'vue'export const API_KEY = Symbol() as InjectionKey<AxiosInstance>
export const THEME_KEY = Symbol() as InjectionKey<'light' | 'dark'>

相关文章:

  • 基于ubuntu24.10安装NACOS2.5.1的简介
  • 第18周:对于ResNeXt-50算法的思考
  • 51单片机实验一:点亮led灯
  • 2025妈妈杯Mathorcup数学建模竞赛选题建议+初步分析
  • 路由交换网络专题 | 第五章 | ISIS | RIP | 路由引入 | 策略路由
  • Crawl4AI:重塑大语言模型数据供给的开源革命者
  • Vue Teleport 及其在 SSR 中的潜在问题
  • 蓝桥杯之前缀和
  • 基于瑞芯微RK3576国产ARM八核2.2GHz A72 工业评估板——Docker容器部署方法说明
  • Ubuntu20.04 部署llama-factory问题集
  • Tensorflow实现用接口调用模型训练和停止训练功能
  • openGauss基于PITR恢复测试
  • 第五章 制作工具优化
  • VUE简介
  • 【 图像梯度处理,图像边缘检测】图像处理(OpenCv)-part6
  • C++(17):通过filesystem获取文件的大小
  • electron 渲染进程按钮创建新window,报BrowserWindow is not a constructor错误;
  • 【go】什么是Go语言的GPM模型?工作流程?为什么Go语言中的GMP模型需要有P?
  • 好数对的数目
  • MySQL事务详解
  • 孙颖莎4比1击败陈幸同,与蒯曼会师澳门世界杯女单决赛
  • 科普|军团菌肺炎:春末夏初的隐形健康威胁
  • 刘国梁:奥运会乒乓球项目增至六金,国乒机遇与挑战并存
  • 一图看懂|特朗普政府VS美国顶尖高校:这场风暴如何刮起?
  • 霸王茶姬成美股“中国茶饮第一股”:首日涨近16%,市值60亿美元
  • 马克龙:美乌欧在法磋商乌克兰问题“积极且有建设性”