vueX的辅助方法

217 阅读1分钟

mapState的用法

mapState可以用于取vuex中state里的存放值,帮助我们将代码进行简化,不需要通过this.$store.state这样的方式去取vuex中存放的值,这在我们需要使用很多次的时候,尤为方便。

import { mapState } from 'vuex'
export default {  
   computed:mapState({  
       cartList:state => state.cartList,
       /*我们也可以新定义一个参数,用于接受cartList,这样组件其他地方用到了,我们可以用this.getCartList 
       来获取*/
       getCartList:'cartList'    
   })  
}

mapMutations的用法

mapMutations是写在methods里面 它触发一个方法可以用于改变vuex中state里面的值 是一个同步的方法

0[OL5_}OM_}UV(JK]~F{Q.png

然后在我们需要的组件或者页面中用mapMutations将changeMsg方法提取出来,之后我们可以调用这方法传值将vuex中state的值进行更改

   import {mapActions} from 'vuex'
   export default {
      methods: {
       ...mapMutations([
         'changeMsg'
       ])
      },
    }

mapActions的用法

mapActions同样是写在methods里面 它是触发mutations里面的方法 是一个异步的方法 我们可以在里面加ajax请求

    import {mapActions} from 'vuex'
     export default {
      methods: {
       ...mapActions([
         'changeMsgAction'
       ])
      },
    }

mapGetters的用法

我们可以理解成它和mapState是一样的,更多的时候我们可以在计算属性computed里面见到mapState与mapGetters,但它也有不同的地方,mapState是将属性进行计算并返回,而mapGetters是将属性进行计算缓存

    import { mapGetters} from 'vuex'
    //store.js
    export default { 
        getCartListLen: state =>{
            return state.cartList.length 
        } 
    }
    //组件
    export default { 
        computed:{
            mapGetters({ getLen:'getCartListLen' }), 
        } 
    }