VUE3组合式API:provide和inject用法

官网传送门

provide

provide() 接受两个参数:第一个参数是要注入的 key,可以是一个字符串或者一个 symbol,第二个参数是要注入的值。

当使用 TypeScript 时,key 可以是一个被类型断言为 InjectionKeysymbolInjectionKey 是一个 Vue 提供的工具类型,继承自 Symbol,可以用来同步 provide()inject() 之间值的类型。

inject

第一个参数是注入的 key。Vue 会遍历父组件链,通过匹配 key 来确定所提供的值。如果父组件链上多个组件对同一个 key 提供了值,那么离得更近的组件将会"覆盖"链上更远的组件所提供的值。如果没有能通过 key 匹配到值,inject() 将返回 undefined,除非提供了一个默认值。

第二个参数是可选的,即在没有匹配到 key 时使用的默认值。

示例

父组件

javascript 复制代码
<script setup lang="ts">
import { ref, provide } from 'vue'
import ChildComponent from '@/views/articles/ChildComponent.vue'
const count = ref(0)
provide('count', count)
provide('num', 1)
</script>
<template>
  <ChildComponent></ChildComponent>
</template>

子组件

javascript 复制代码
<script setup lang="ts">
import { inject } from 'vue'

const count = inject('count')
const num = inject('num')
const other = inject('other')
const otherDefault = inject('otherDefault', 'default')
console.log(other)
</script>
<template>
  <div>count:{{ count }}</div>
  <div>num:{{ num }}</div>
  <div>other:{{ other }}</div>
  <div>otherDefault:{{ otherDefault }}</div>
</template>

父组件使用provide注入countnum,子组件使用provide注入一个由祖先组件或整个应用 提供的值。在子组件中countnum为父组件注入的值。other为undefined,otherDefault值为默认值default

相关推荐
木斯佳1 小时前
前端八股文面经大全:快手电商日常实习前端一面(2026-05-15)·面经深度解析
前端·面试·面经
2601_958492558 小时前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
茉莉玫瑰花茶9 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
zhangxingchao9 小时前
AI应用开发六:企业知识库
前端·人工智能·后端
山峰哥10 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙10 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying10 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙10 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang45310 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端