关于vue.js:Vue3-优雅实现-useMap

4次阅读

共计 1638 个字符,预计需要花费 5 分钟才能阅读完成。

前言

Vue3 中咱们经常须要用到很多 hook 🔧 工具库。

👨‍🏫 这章介绍如何优雅的实现 useMap,开启高逼格之路。

👏 欢送大家应用体验高质量 vue3-hooks-plus 完满反对 ts

💻 体验地址

实现原理

Map 对象大家肯定都不生疏,那么咱们在 Vue3 中如何很优雅的应用它呢?

1、首先,它得必须具备 Map 的 👇

  • 可传入初始值
  • 增删查改
  • 重置
  • 清空
  • 🌟 响应式

2、既然用了 Vue3 当然要具备响应式啦!

  const initialMap = initialValue ? new Map(initialValue) : new Map()
  const state = ref(initialMap) as Ref<Map<K, T>>

如果有初始值贼赋值初始值,否则给予空 Map。这里就有小伙伴问了,KT 是啥玩意?👇 当然是反对 ts 了,还不会 ts 的小伙伴连忙安顿,这样应用 vue3 能力得心应手。

3、书写 ts 类型文件

type MapValue<K, T> = Iterable<readonly [K, T]>
​
type Actions<K, T> = {set: (key: K, value: T) => void
  get: (key: K) => T | undefined
  remove: (key: K) => void
  has: (key: K) => boolean
  clear: () => void
  setAll: (newMap: MapValue<K, T>) => void
  reset: () => void}

这里的 MapValue 初始值采纳了内置 的 ES6 类型 Iterable , 并且初始值咱们心愿它是只可读的。K 和 T 别离代表 Map 的 键和值。

4、书写 hook

function useMap<K, T>(initialValue?: MapValue<K, T>) {
 ...
 ...
 return [state, markRaw(actions)]
}

state 为 map 的对象,action 为对 map 的操作行为。markRaw 避免其变成 proxy 对象。

源码

import {ref, Ref, markRaw} from 'vue'
​
type MapValue<K, T> = Iterable<readonly [K, T]>
​
type Actions<K, T> = {set: (key: K, value: T) => void
  get: (key: K) => T | undefined
  remove: (key: K) => void
  has: (key: K) => boolean
  clear: () => void
  setAll: (newMap: MapValue<K, T>) => void
  reset: () => void}
​
function useMap<K, T>(initialValue?: MapValue<K, T>): [Ref<Map<K, T>>, Actions<K, T>]
​
function useMap<K, T>(initialValue?: MapValue<K, T>) {const initialMap = initialValue ? new Map(initialValue) : new Map()
  const state = ref(initialMap) as Ref<Map<K, T>>
​
  const actions: Actions<K, T> = {set: (key, value) => {state.value.set(key, value)
    },
    get: (key) => {return state.value.get(key)
    },
    remove: (key) => {state.value.delete(key)
    },
    has: (key) => state.value.has(key),
    clear: () => state.value.clear(),
    setAll: (newMap) => {state.value = new Map(newMap)
    },
    reset: () => (state.value = initialMap),
  }
​
  return [state, markRaw(actions)]
}
​
export default useMap
​

附言

⛽️ 加油,早日成为巨佬

正文完
 0