Skip to content

useArrayReduce

Category
Export Size
171 B
Last Changed
15 minutes ago

响应式 Array.reduce

用法

js
import { useArrayReduce } from '@vueuse/core'

const sum = useArrayReduce([ref(1), ref(2), ref(3)], (sum, val) => sum + val)
// sum.value: 6

与响应式数组一起使用

js
import { useArrayReduce } from '@vueuse/core'

const list = reactive([1, 2])
const sum = useArrayReduce(list, (sum, val) => sum + val)

list.push(3)
// sum.value: 6

与初始值一起使用

js
import { useArrayReduce } from '@vueuse/core'

const list = reactive([{ num: 1 }, { num: 2 }])
const sum = useArrayReduce(list, (sum, val) => sum + val.num, 0)
// sum.value: 3

类型声明

typescript
export type UseArrayReducer<PV, CV, R> = (
  previousValue: PV,
  currentValue: CV,
  currentIndex: number,
) => R
/**
 * 响应式 `Array.reduce`
 *
 * @see https://vueuse.org/useArrayReduce
 * @param list - 被调用的数组。
 * @param reducer - 一个“reducer”函数。
 *
 * @returns 在整个数组上运行“reducer”回调函数完成后的值。
 */
export declare function useArrayReduce<T>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  reducer: UseArrayReducer<T, T, T>,
): ComputedRef<T>
/**
 * 响应式 `Array.reduce`
 *
 * @see https://vueuse.org/useArrayReduce
 * @param list - 被调用的数组。
 * @param reducer - 一个“reducer”函数。
 * @param initialValue - 在第一次调用回调函数时初始化的值。
 *
 * @returns 在整个数组上运行“reducer”回调函数完成后的值。
 */
export declare function useArrayReduce<T, U>(
  list: MaybeRefOrGetter<MaybeRefOrGetter<T>[]>,
  reducer: UseArrayReducer<U, T, U>,
  initialValue: MaybeRefOrGetter<U>,
): ComputedRef<U>

Source

SourceDocs

贡献者

Anthony Fu
丶远方
Mutter
Anthony Fu
Levi (Nguyễn Lương Huy)
XLor

变更日志

v11.2.0 on 10/30/2024
ae542 - fix: initialValue can be a function (#4243)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue

Released under the MIT License.