Vuex 辅助函数的运用

 
//在需要获取的页面引入
import {mapState,mapGetters,mapMutations,mapActions} from "vuex";
mapState的使用方法:
export default {
    computed:{
        //第一种写法
        count(){
          return this.$store.state.count;          
        },
        //第二种 通过辅助函数的方式 (当state声明的名称和获取的一样时)
        ...mapState(['count','username']) //获取
        //第三种 通过辅助函数的方式 (当state声明的名称和获取的不一样时)
        ...mapState({
            myCount: 'count',
            user: 'username'        
        })
    },
}
mapGetters的使用方法:
1、在store/index.js中定义
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count:0    
    },
    getters:{
       evenOrOdd(states){
           return state.count % 2 === 0 ? '偶数' : '奇数'       
       } 
    }
})
2、在需要的组件页获取
computed:{
    //第一种
    evenOrOdd(){
        return this.$store.getters.count;
    }
    //第二种通过辅助函数的方式
    ...mapGetters(['evenOrOdd'])
}
mapMutations的使用方法:
 methods:{
   //第一种
   handleAddCount(){
      this.$store.commit('increment') //increment 是store/index.js中actions中声明的方法
   }
   //第二种通过辅助函数的方式
   ...mapMutations(['increment','test2'])
}
mapActions的使用方法:
 methods:{
     //第一种
   handleAddCount(){
          this.$store.dispatch('increment') //increment 是store/index.js中actions中声明的方法
   },
   //第二种通过辅助函数的方式
   ...mapActions(['increment'])
}

 

 
posted @ 2021-06-10 19:09  是娜娜呀~  阅读(150)  评论(0)    收藏  举报