Skip to content
On this page

useMap

优雅的管理 Map 结构数据

Demo

Map:{ "Map(2)": { "a =>": 1, "b =>": 2 } }

get 获取到的值:

has 获取到的值:false

Usage

html
<template>
  <div>
    <p>Map:{{ state }}</p>
    <p>get 获取到的值:{{ actionMapValue }}</p>
    <p>has 获取到的值:{{ hasValue }}</p>

    <button @click="set('a', Math.random())">设置 A</button>
    <button @click="setAll([['a', Math.random()]])">设置所有 Map</button>
    <button @click="remove('a')">删除 A</button>
    <button @click="reset()">重置</button>
    <button
      @click="
        () => {
          actionMapValue = get('a')
        }
      "
    >
      获取 A
    </button>
    <button
      @click="
        () => {
          hasValue = has('a')
        }
      "
    >
      判断有无 A
    </button>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useMap } from '@morehook/core'

const actionMapValue = ref()
const hasValue = ref(false)

const [state, { set, setAll, get, remove, has, reset }] = useMap([
  ['a', 1],
  ['b', 2]
])
</script>

Type Declarations

typescript
type MapValue = readonly (readonly [any, any])[]
/**
 * set: 新增数据
 * get: 获取数据
 * remove: 删除数据
 * has: 判断是否有某条数据
 * clear: 清除某条数据
 * setAll: 设置所有数据
 * reset: 清除所有数据
 */
interface Actions<T> {
  set: (key: string, value: T) => void
  get: (key: string) => T
  remove: (key: string) => void
  has: (key: string) => boolean
  clear: () => void
  setAll: (newMap: MapValue) => void
  reset: () => void
}
/**
 * 操作 Map
 * @param initialValue map 初始值
 * @returns state: map源数据,actions: Actions
 */
export declare function useMap<T = any>(
  initialValue?: MapValue
): [state: Ref<Map<any, any>>, actions: Actions<T>]

Source

SourceDemoDocs