vue3在setup中使用mapState解讀
vue3 setup使用mapState
mapState和computed結(jié)合在Vue3版本中使用,廣大網(wǎng)友寫了很多,這里只做一個實戰(zhàn)后的應(yīng)用筆記,不多贅述
創(chuàng)建一個hook
hooks/useMapState.ts
import { computed } from "vue"
import { mapState, useStore } from "vuex"
export default function (state:any) {
? ? // 1. 獲取實例 $store
? ? const store = useStore()
? ? // 2. 遍歷狀態(tài)數(shù)據(jù)
? ? const storeStateFns = mapState(state)
? ? // 3. 存放處理好的數(shù)據(jù)對象
? ? const storeState = {}
? ? // 4. 對每個函數(shù)進行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中的多個State,我們經(jīng)過會借助mapState輔助函數(shù)進行獲取值,但是在Vue3中,通過computed的來獲取多個值的方法官方并未提供,話不多說,直接上代碼。
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進行返回,所以只能按照如下方式寫了
在setup語法糖中使用
<script setup>
import { useMapState } from ''./Hooks/useMapState.js'
const { title, counter } = useMapState(['title', 'counter'])
</script>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- vue3中setup語法糖下父子組件間傳遞數(shù)據(jù)的方式
- Vue3.2中setup語法糖的使用教程分享
- vue3中<script?setup>?和?setup函數(shù)的區(qū)別對比
- Vue3?setup的注意點及watch監(jiān)視屬性的六種情況分析
- Vue3中關(guān)于setup與自定義指令詳解
- Vue3中的setup語法糖、computed函數(shù)、watch函數(shù)詳解
- Vue3?setup?的作用實例詳解
- Vue3?setup添加name的方法步驟
- Vue3的setup在el-tab中動態(tài)加載組件的方法
- vue3.0?setup中使用vue-router問題
- vue3中setup語法糖下通用的分頁插件實例詳解
- vue3?setup語法糖各種語法新特性的使用方法(vue3+vite+pinia)
- vue3 setup的使用和原理實例詳解
相關(guān)文章
在Vue中使用this.$store或者是$route一直報錯的解決
今天小編就為大家分享一篇在Vue中使用this.$store或者是$route一直報錯的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

