vue3在setup中使用mapState解讀
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è)參考,也希望大家多多支持腳本之家。
- vue3中setup語法糖下父子組件間傳遞數(shù)據(jù)的方式
- Vue3.2中setup語法糖的使用教程分享
- vue3中<script?setup>?和?setup函數(shù)的區(qū)別對(duì)比
- Vue3?setup的注意點(diǎn)及watch監(jiān)視屬性的六種情況分析
- Vue3中關(guān)于setup與自定義指令詳解
- Vue3中的setup語法糖、computed函數(shù)、watch函數(shù)詳解
- Vue3?setup?的作用實(shí)例詳解
- Vue3?setup添加name的方法步驟
- Vue3的setup在el-tab中動(dòng)態(tài)加載組件的方法
- vue3.0?setup中使用vue-router問題
- vue3中setup語法糖下通用的分頁插件實(shí)例詳解
- vue3?setup語法糖各種語法新特性的使用方法(vue3+vite+pinia)
- vue3 setup的使用和原理實(shí)例詳解
相關(guān)文章
簡(jiǎn)單學(xué)習(xí)5種處理Vue.js異常的方法
這篇文章主要介紹了簡(jiǎn)單學(xué)習(xí)5種處理Vue.js異常的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06在Vue中使用this.$store或者是$route一直報(bào)錯(cuò)的解決
今天小編就為大家分享一篇在Vue中使用this.$store或者是$route一直報(bào)錯(cuò)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11基于vue2.0動(dòng)態(tài)組件及render詳解
下面小編就為大家分享一篇基于vue2.0動(dòng)態(tài)組件及render詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03