vuex@4.x 在vue3中使用 封装useState函数

685 阅读1分钟

vuex@4.x 在vue3中使用 封装useState函数

安装

npm install vuex@next

在composition Api中 封装共用hook

store/index.js


const store = createStore({
    state() {
        return {
            name: "ddd",
            age: 18,
            sex: '女'
        }
    }
})
export default store

hooks/useState.js

import { mapState, useStore } from 'vuex';
export function useState(mapper) {
    //拿到store对象
    const store = useStore()

    //获取对应的对象functions:{name:function,age:function}
    const storeStateFns = mapState(mapper)

    //对数据进行转化  将对象转为ref数据
    const storeState = {}
    Object.keys(storeStateFns).forEach(fnKey => {
        //bind 绑定store对象 解决拿不到this的问题
        const fn = storeStateFns[fnKey].bind({ $store: store })
        storeState[fnKey] = computed(fn)
    })
    return storeState
}

使用该hook

import { useState } from "../hooks/useState";
export default {
  setup() {
    //useState 不仅支持数组也支持对象 代替了 const ddd = computed(()=>store.state.name)
    const storeState = useState(["name", "sex", "age"]);
    const storeState2 = useState({
      dName: (state) => state.name,
    });
    return {
      ...storeState,
      storeState2,
    };
  },
};
</script>