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
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM