Vue3 优雅实现 useMap
前言
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。这里就有小伙伴问了,K
和 T
是啥玩意? 👇 当然是支持 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
附言
⛽️ 加油,早日成为巨佬
转载自:https://segmentfault.com/a/1190000041726535