vuex-map四个方法使用

140 阅读1分钟

mapState方法:用于帮助映射state中的数据为计算属性 用mapState等这种辅助函数的时候,前面的方法名和获取的属性名是一致的

computed:{
   //借助mapstate生成计算属性:name,gage,gender(对象写法)
    ...mapState({name:'name',age:'age',gender:'gender'})
    
    //借助mapstate生成计算属性:name,gage,gender(数组写法)
    ...mapState(['name','age','gender'])
    }

mapGetters方法:用于帮助映射getters中的数据为计算属性

computed:{
   //借助mapGetters生成计算属性:bigSum(对象写法)
    ...mapGetters({bigSum:'bigSum'})
    
    //借助mapGetters生成计算属性:bigSum(数组写法)
    ...mapGetters(['bigSum'])
    }

mapActions方法:用于帮助生成与action对话的方法,即包含$store.dispatch(xxx)的函数

methods:{
    //靠mapActions生成:incrementOdd,incrementWait(对象形式)
    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    //靠mapActions生成:incrementOdd,incrementWait(数组形式)
     ...mapActions(['jiaOdd','jiaWait'])
     }
     

mapMutation方法:用于帮助生成与mutations对话方法,即包含$store.commit(xxx)函数

 代码中定义的时候需要些mutations,它类似于vue中的methods,
 mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是    state,第二个参数是载荷(payLoad),也就是额外的参数
  
mutations: { //类似于methods
  addAge(state,payLoad){
     state.age+=payLoad.number
  }
}

template部分
<div class="home">
   <div><button @click="test">测试</button></div>
</div>

js部分
methods:{
 test(){
   this.$store.commit('addAge',{
     number:5
   })
 }
}

image.png