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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript的Vue.js庫入門學(xué)習(xí)教程
Vue的很多思想借鑒于Angular,但卻比較輕量和自由,這里我們整理了JavaScript的Vue.js庫入門學(xué)習(xí)教程,包括其架構(gòu)思想與核心的數(shù)據(jù)綁定方式等,需要的朋友可以參考下2016-05-05
使用Vue-scroller頁面input框不能觸發(fā)滑動的問題及解決方法
這篇文章主要介紹了使用Vue-scroller頁面input框不能觸發(fā)滑動的問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
解決vant的Cascader級聯(lián)選擇組建css樣式錯亂問題
這篇文章主要介紹了解決vant的Cascader級聯(lián)選擇組建css樣式錯亂問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
vue中input標簽上傳本地文件或圖片后獲取完整路徑的解決方法
本文給大家介紹vue中input標簽上傳本地文件或圖片后獲取完整路徑,如E:\medicineOfCH\stageImage\xxx.jpg,本文給大家分享完美解決方案,感興趣的朋友跟隨小編一起看看吧2023-04-04

