Skip to content

computedInject

类别
导出体积
142 B
上次更改
3 months ago

结合 computed 和 inject 使用

示例

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

祖先组件

ts
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
)
js
import { provide } 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)

后代组件

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

类型声明

显示类型声明
ts
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
>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
丶远方
SerKo
Zhong
IlyaL
wheat
MinatoHikari

更新日志

0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)