主题
computedInject
将 computed 和 inject 组合。适用于根据注入的值创建计算属性。
🌐 Combine computed and inject. Useful for creating a computed property based on an injected value.
示例
Array
[
{
"key": 1,
"value": "1"
},
{
"key": 2,
"value": "2"
},
{
"key": 3,
"value": "3"
}
] Computed Array
[
{
"key": 0,
"value": "all"
},
{
"key": 1,
"value": "1"
},
{
"key": 2,
"value": "2"
},
{
"key": 3,
"value": "3"
}
]用法
🌐 Usage
在提供者组件中
🌐 In Provider Component
ts
import type { InjectionKey, Ref } from 'vue'
import { provide, ref } 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)js
import { provide, ref } from 'vue'
export const ArrayKey = Symbol('symbol-key')
const array = ref([
{ key: 1, value: '1' },
{ key: 2, value: '2' },
{ key: 3, value: '3' },
])
provide(ArrayKey, array)在接收器组件中
🌐 In Receiver Component
ts
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
})默认值
🌐 Default Value
如果父组件没有提供注入键,你可以提供一个默认值将被使用。
🌐 You can provide a default value that will be used if the injection key is not provided by a parent component.
ts
import { computedInject } from '@vueuse/core'
const computedArray = computedInject(
ArrayKey,
(source) => {
return source.value.map(item => item.value)
},
ref([]), // default source value
)js
import { computedInject } from '@vueuse/core'
const computedArray = computedInject(
ArrayKey,
(source) => {
return source.value.map((item) => item.value)
},
ref([]),
)出厂设置
🌐 Factory Default
将 true 作为第四个参数传入,以将默认值视为工厂函数。
🌐 Pass true as the fourth argument to treat the default value as a factory function.
ts
import { computedInject } from '@vueuse/core'
const computedArray = computedInject(
ArrayKey,
(source) => {
return source.value.map(item => item.value)
},
() => ref([]), // factory function for default
true, // treat default as factory
)js
import { computedInject } from '@vueuse/core'
const computedArray = computedInject(
ArrayKey,
(source) => {
return source.value.map((item) => item.value)
},
() => ref([]), // factory function for default
true,
)可写计算
🌐 Writable Computed
你也可以通过传入包含 get 和 set 函数的对象来创建一个可写的计算属性。
🌐 You can also create a writable computed property by passing an object with get and set functions.
ts
import { computedInject } from '@vueuse/core'
const computedArray = computedInject(ArrayKey, {
get(source) {
return source.value.map(item => item.value)
},
set(value) {
// handle setting the value
console.log('Setting value:', value)
},
})