VUE3组合式API:provide和inject用法

官网传送门

provide

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

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

inject

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

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

示例

父组件

<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>

子组件

<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为父组件注入的值。otherundefinedotherDefault值为默认值default

你可能感兴趣的:(VUE3,vue.js,javascript,前端)