傳統方式
setup() { const store = useStore() //傳統方式 const aName = computed(() => store.state.name) return { aName }
如果數據多一點一個一個導入就十分的不方便
我們可以使用這樣一種方法
setup() { const store = useStore() //如果想一次拿到想要的數據 const storeStateFns = mapState(["counter", "name"]) //console.log(storeState[1]); //這里的storeState展開后的"counter","name"其實是一個一個的函數,counter:function(){} //使用computed對其進行解構 //name:function(){},鍵值對函數,拿到key(name) //Object.keys()返回的是一個數組類型 const storeState={} Object.keys(storeStateFns).forEach(fnKey=>{ //綁定store,setup中沒有this const fn = storeStateFns[fnKey].bind({$store:store}); //computed生成ref storeState[fnKey] = computed(fn) }) return { ...storeState } }
將其封裝成單個js文件的模塊
// default導出的函數在引用時不需要大括號 import {computed} from "vue"; import {mapState, useStore} from "vuex"; //注意這里的mapper是一個數組或對象,因為mapState可以解析數組和對象 export default function useState(mapper) { //拿到store獨享 const store = useStore() //獲取到對應的functions:{name: function() {},counter: function() {}} const storeStateFns = mapState(mapper) //對數據進行轉換 const storeState = {} Object.keys(storeStateFns).forEach(fnKey => { const fn = storeStateFns[fnKey].bind({$store: store}); storeState[fnKey] = computed(fn) }) return storeState }
