zoukankan      html  css  js  c++  java
  • 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中对应起来
     })
    
  • 相关阅读:
    计蒜客模拟赛D2T2 蒜头君的排序:区间逆序对(移动端点) + 树状数组
    计蒜客模拟赛D2T1 蒜头君的兔子:矩阵快速幂
    计蒜客模拟赛D1T2 蒜头君的树:树上节点之间最短距离和
    计蒜客模拟赛D1T1 蒜头君打地鼠:矩阵旋转+二维前缀和
    Cubieboard安装系统
    awk速查手册
    sed速查手册
    常用正则表达
    MySQL索引小记
    jQuery中attr和prop的区别
  • 原文地址:https://www.cnblogs.com/xyf724/p/13279616.html
Copyright © 2011-2022 走看看