亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue3在setup中使用mapState解讀

 更新時(shí)間:2023年04月19日 08:36:45   作者:mrhaoxiaojun  
這篇文章主要介紹了vue3在setup中使用mapState方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue3 setup使用mapState

mapState和computed結(jié)合在Vue3版本中使用,廣大網(wǎng)友寫了很多,這里只做一個(gè)實(shí)戰(zhàn)后的應(yīng)用筆記,不多贅述

創(chuàng)建一個(gè)hook

hooks/useMapState.ts

import { computed } from "vue"
import { mapState, useStore } from "vuex"
export default function (state:any) {
? ? // 1. 獲取實(shí)例 $store
? ? const store = useStore()
? ? // 2. 遍歷狀態(tài)數(shù)據(jù)
? ? const storeStateFns = mapState(state)
? ? // 3. 存放處理好的數(shù)據(jù)對(duì)象
? ? const storeState = {}
? ? // 4. 對(duì)每個(gè)函數(shù)進(jìn)行computed
? ? Object.keys(storeStateFns).forEach(fnKey => {
? ? ? ? const fn = storeStateFns[fnKey].bind({ $store: store })
? ? ? ? // 遍歷生成這種數(shù)據(jù)結(jié)構(gòu) => {name: ref(), age: ref()}
? ? ? ? storeState[fnKey] = computed(fn)
? ? })
? ? return storeState
}

使用

<script lang="ts" setup>

import useMapState from "@/hooks/useMapState"

const myState:any = useMapState({
? includeList: (state: any) => state.keepAlive.includeList
})
const { includeList } = myState
</script>

vue3 setup語法糖中使用mapState

在Vue的組件中,要想使用Vuex中的多個(gè)State,我們經(jīng)過會(huì)借助mapState輔助函數(shù)進(jìn)行獲取值,但是在Vue3中,通過computed的來獲取多個(gè)值的方法官方并未提供,話不多說,直接上代碼。

useMapState.js

import { computed } from "vue";
import { mapState, useStore } from "vuex"

export const useMapState = (getKeys) => {

? ? const store = useStore();
? ??
? ? const storeState = {}
? ? const storeFns = mapState(getKeys)

? ? Object.keys(storeFns).forEach((fnKeys) => {
? ? ? ? const fn = storeFns[fnKeys].bind({$store: store})
? ? ? ? storeState[fnKeys] = computed(fn)
? ? })

? ? return storeState
}

在setup函數(shù)中使用

<script>
import { useMapState } from ''./Hooks/useMapState.js'

export default {
? ? setup() {
? ? ? ? const storeState = useMapState(['title', 'counter'])

? ? ? ? return {
? ? ? ? ? ? ...storeState
? ? ? ? }
? ? }
}

</script>

在setup語法糖中由于不能使用 return進(jìn)行返回,所以只能按照如下方式寫了

在setup語法糖中使用

<script setup>
import { useMapState } from ''./Hooks/useMapState.js'

const { title, counter } = useMapState(['title', 'counter'])

</script>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論