• Vuex的辅助函数mapState, mapActions, mapMutations用法


    直接代码解说

    store/index.js (简单书写)

    export default new Vuex.Store({
        state: {
            add: 10
        },
        mutations: {
            change(state,a) {
                state.add += a
            }
        }
    })
    

    在一般的情况下,我们想要拿到add这个值,就需要使用this. $store.state.add来获取,但是这样的代码片段太长了

    前提:

    import { mapState, mapActions, mapMutations} from 'vuex'
    //使用都分为两种方式:对象和数组,但是自我推荐,使用对象的形式,更加有利于理解
    

    mapState的使用

    computed: {
        //第一种方式
        ...mapState({
            add: state => state.add
        })
        //第二种方式,以数组的方式
        ...mapState(['add'])  //必须要加冒号
    }
    
    

    mapMutations的使用

    //调用Mutations 需要时使用 this.$store.commit('change', 1) 这样的
    
    //第一种方式,使用数组的形式
    ...mapMutations(['change']), // 会将 this.change 映射成 this.$store.commit('change') 
    //第二种方式,使用对象的形式
    ...mapMutations({
        'change': 'change'  //前面这个属性可以随便写,但是后面的属性值要与mutations中对应起来
     })
    //传参: 跟普通的方法一样,直接把参数写在调用函数的括号里,就OK了。
    

    mapActions的使用(对异步函数的操作)

    //调用Actions 需要时使用 this.$store.dispatch('asyn', 1) 这样的
    
    //第一种方式,使用数组的形式
    ...mapActions(['asyn']), // 会将 this.asyn 映射成 this.$store.dispatch('asyn') 
    //第二种方式,使用对象的形式
    ...mapActions({
        'asyn': 'asyn'  //前面这个属性可以随便写,但是后面的属性值要与actions中对应起来
     })
    
  • 相关阅读:
    HDOJ/HDU 2560 Buildings(嗯~水题)
    HDOJ/HDU 2555 人人都能参加第30届校田径运动会了(判断加排序~)
    POJ1703Find them, Catch them
    BZOJ2303: [Apio2011]方格染色
    BZOJ2809: [Apio2012]dispatching
    POJ1611The Suspects
    BZOJ2006: [NOI2010]超级钢琴
    BZOJ2288: 【POJ Challenge】生日礼物
    BZOJ1150: [CTSC2007]数据备份Backup
    洛谷P1316 P1824
  • 原文地址:https://www.cnblogs.com/xyf724/p/13279616.html
Copyright © 2020-2023  润新知