Vuex

168 阅读1分钟

vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。即用于管理全局共享数据的。

  • 解决多层组件嵌套参数传递的问题

store

每一个 Vuex 应用的核心就是 store(仓库)。

  • 创建store对象
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    getcount: state => {
      return state.count
    }
  }
  mutations: {
    increment (state,payload) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

核心概念

State

存储在 Vuex 中的数据,相当于组件中的data;

  • 获取vuex中数据的方法 (1)通过属性访问:this.$store.state.xxx (2)在computed中返回某个状态

Getters

  • 通过属性访问:this.$store.getters.xxx
  • 通过方法访问:

Mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

  • this.$store.commit('xxx')
  • 提交载荷(Payload):this.$store.commit('xxx', 10)

Actions

Action 可以包含任意异步操作。

  • this.$store.dispatch('increment')
  • 提交payload:this.$store.dispatch('incrementAsync', { amount: 10})

Modules

将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter;

辅助函数map*

  • mapState\mapGetter 1、以对象的形式
import { mapState,mapGetters  } from 'vuex'
export default {
  computed: {
      ...mapState({
        count: state => state.count,
        // 传字符串参数 'count' 等同于 `state => state.count`
      }),
      ...mapGetters({
          // 把 `this.getcount` 映射为 `this.$store.getters.getcount`
          getcount: 'getcount'
       })
  }
}

2、以数组字符串的形式

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  // 映射 this.count 为 store.state.count
     ...mapState([     'count'     ]),
     ...mapGetters([      'getcount',    ])
}
  • mapMutations/mapActions 1、以对象的形式/数组形式
import { mapMutations } from 'vuex'
export default {
  methods: {
  //数组字符串形式
    ...mapMutations([      'increment',     ]),
    ...mapActions([      'increment',    ]),
    //对象的形式
     ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    }),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

Vuex模块化用法 跨模块调用方法

原文链接:blog.csdn.net/qq_42268364…