computedInject
computedInject 是一种实用工具,可让您结合 Vue 的 computed 属性和 inject 函数的功能。它允许您从祖先组件注入响应式数据,并在此数据上创建派生计算属性。
用法
在提供者组件中
首先,您需要在提供数据的祖先组件中使用 provide 来提供数据。建议为注入键使用 Symbol 以避免命名冲突。
import type { InjectionKey, Ref } from 'vue'
import { provide } from 'vue'
interface Item {
key: number
value: string
}
export const ArrayKey: InjectionKey<Ref<Item[]>> = Symbol('symbol-key')
const array = ref([{ key: 1, value: '1' }, { key: 2, value: '2' }, { key: 3, value: '3' }])
provide(ArrayKey, array)
在接收者组件中
在子孙组件中,您可以使用 computedInject 来注入数据并对其执行计算。
import { computedInject } from '@vueuse/core'
import { ArrayKey } from './provider' // 从提供者组件导入注入键
const computedArray = computedInject(ArrayKey, (source) => {
const arr = [...source.value]
arr.unshift({ key: 0, value: 'all' }) // 在数组开头添加一个新项
return arr
})
在这个例子中,computedArray 将是 source 数组的一个计算版本,其中在开头添加了一个 key: 0, value: 'all' 的项。当 source 数组发生变化时,computedArray 将自动更新。
类型声明
export type ComputedInjectGetter<T, K> = (
source: T | undefined,
oldValue?: K,
) => K
export type ComputedInjectGetterWithDefault<T, K> = (
source: T,
oldValue?: K,
) => K
export type ComputedInjectSetter<T> = (v: T) => void
export interface WritableComputedInjectOptions<T, K> {
get: ComputedInjectGetter<T, K>
set: ComputedInjectSetter<K>
}
export interface WritableComputedInjectOptionsWithDefault<T, K> {
get: ComputedInjectGetterWithDefault<T, K>
set: ComputedInjectSetter<K>
}
export declare function computedInject<T, K = any>(
key: InjectionKey<T> | string,
getter: ComputedInjectGetter<T, K>,
): ComputedRef<K | undefined>
export declare function computedInject<T, K = any>(
key: InjectionKey<T> | string,
options: WritableComputedInjectOptions<T, K>,
): ComputedRef<K | undefined>
export declare function computedInject<T, K = any>(
key: InjectionKey<T> | string,
getter: ComputedInjectGetterWithDefault<T, K>,
defaultSource: T,
treatDefaultAsFactory?: false,
): ComputedRef<K>
export declare function computedInject<T, K = any>(
key: InjectionKey<T> | string,
options: WritableComputedInjectOptionsWithDefault<T, K>,
defaultSource: T | (() => T),
treatDefaultAsFactory: true,
): ComputedRef<K>