vuex

作者: 开车去环游世界 | 来源:发表于2017-02-05 11:50 被阅读224次

    http://www.imooc.com/article/14741

    mapState

    import { mapState } from 'vuex'
    export default {
      // ...
      computed: mapState({
        // 箭头函数可以让代码非常简洁
        count: state => state.count,
        // 传入字符串 'count' 等同于 `state => state.count`
        countAlias: 'count',
        // 想访问局部状态,就必须借助于一个普通函数,函数中使用 `this` 获取局部状态
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
      })
    }
    

    经过 mapState 函数调用后的结果,如下所示:

    import { mapState } from 'vuex'
    export default {
      // ...
      computed: {
        count() {
          return this.$store.state.count
        },
        countAlias() {
          return this.$store.state['count']
        },
        countPlusLocalState() {
          return this.$store.state.count + this.localCount
        }
      }
    }
    

    mapGetters

    mapGetters 的实现也和 mapState 很类似,不同的是它的 val 不能是函数,只能是一个字符串,而且会检查 val in this.$store.getters 的值,如果为 false 会输出一条错误日志。

    import { mapGetters } from 'vuex'
    export default {
      // ...
      computed: {
        // 使用对象扩展操作符把 getter 混入到 computed 中
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter',
          // ...
        ])
      }
    }
    

    经过 mapGetters 函数调用后的结果,如下所示:

    import { mapGetters } from 'vuex'
    export default {
      // ...
      computed: {
        doneTodosCount() {
          return this.$store.getters['doneTodosCount']
        },
        anotherGetter() {
          return this.$store.getters['anotherGetter']
        }
      }
    }
    

    mapMutations

    函数的实现几乎也和 mapActions 一样,唯一差别就是映射的是 store 的 commit 方法。为了更直观地理解,我们来看一个简单的例子

    import { mapMutations } from 'vuex'
    export default {
      // ...
      methods: {
        ...mapMutations([
          'increment' // 映射 this.increment() 到 this.$store.commit('increment')
        ]),
        ...mapMutations({
          add: 'increment' // 映射 this.add() 到 this.$store.commit('increment')
        })
      }
    }
    

    经过 mapMutations 函数调用后的结果,如下所示:

    import { mapActions } from 'vuex'
    export default {
      // ...
      methods: {
        increment(...args) {
          return this.$store.commit.apply(this.$store, ['increment'].concat(args))
        }
        add(...args) {
          return this.$store.commit.apply(this.$store, ['increment'].concat(args))
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:vuex

          本文链接:https://www.haomeiwen.com/subject/zoteittx.html