Skip to content
On this page

useMethods

一个 useReducer 简化版的 Hook

Demo

0
<template>
<div>{{ state.count }}</div>
<button @click="dispatch.increment()">inc()</button>
<button @click="dispatch.decrement()">dec()</button>
<button @click="dispatch.reset()">reset()</button>
</template>

<script setup lang="ts">
import { useMethods } from 'v3-use'

type State = {
count: number
}

const initialCount = {
count: 0
}

function reducer(state: State) {
return {
increment() {
return { count: state.count + 1 }
},
decrement() {
return { count: state.count - 1 }
},
reset() {
return { count: 0 }
}
}
}

const [state, dispatch] = useMethods(reducer, initialCount)
</script>

Usage

import { useMethods } from 'v3-use'

type State = {
  count: number
}

const initialCount = {
  count: 0
}

const reducer = (state: State) => {
  return {
    increment () {
      return { count: state.count + 1 }
    },
    decrement () {
      return { count: state.count - 1 }
    },
    reset () {
      return { count: 0 }
    }
  }
}

const [state, dispatch] = useMethods(reducer, initialCount)
</script>
import { useMethods } from 'v3-use'

type State = {
  count: number
}

const initialCount = {
  count: 0
}

const reducer = (state: State) => {
  return {
    increment () {
      return { count: state.count + 1 }
    },
    decrement () {
      return { count: state.count - 1 }
    },
    reset () {
      return { count: 0 }
    }
  }
}

const [state, dispatch] = useMethods(reducer, initialCount)
</script>

Reference

const [state, dispatch] = useMethods<M, T> (
  createMethods: CreateMethods<M, T>,
  initialState: T
)
const [state, dispatch] = useMethods<M, T> (
  createMethods: CreateMethods<M, T>,
  initialState: T
)

Type Declarations

export declare type ReducerAction<T = string, P = any> = {
  type: T
  payload?: P
}
export declare type CreateMethods<M, T> = (state: T) => {
  [P in keyof M]: (payload?: any) => T
}
export declare type WrappedMethods<M> = {
  [P in keyof M]: (...payload: any) => void
}
export declare function useMethods<M, T>(
  createMethods: CreateMethods<M, T>,
  initialState: T
): [Ref<T>, WrappedMethods<M>]
export declare type ReducerAction<T = string, P = any> = {
  type: T
  payload?: P
}
export declare type CreateMethods<M, T> = (state: T) => {
  [P in keyof M]: (payload?: any) => T
}
export declare type WrappedMethods<M> = {
  [P in keyof M]: (...payload: any) => void
}
export declare function useMethods<M, T>(
  createMethods: CreateMethods<M, T>,
  initialState: T
): [Ref<T>, WrappedMethods<M>]

Params

  • createMethods: CreateMethods — 简化版 reducer 函数,返回包含方法的对象
  • initialState: T — 初始 state

Result

  • state: Ref<T> — 状态值
  • dispatch: WrappedMethods — 调度函数集合,触发状态更新