1. 程式人生 > 其它 >vue3-元件中使用setup函式獲取vuex中的資料的新方式

vue3-元件中使用setup函式獲取vuex中的資料的新方式

傳統方式

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 }