Vuex是什么

Vuex是一个针对Vue.js开发的状态管理模式。说简单点儿就是一个工具,可以管理(修改或设置)所有组件用到的数据,而不需要借助之前的event bus或者props在组件间传值。

Vuex使用场景

大型单页应用程序,存在多组件共享数据的时候,需要用到
Vuex 核心内容

store

(一个容器对象,存储Vuex中的state,mutations,actions,getters等)

  • state (一个保存数据的对象,对象中的数据可以供所有组件使用)

    // 1. 定义
    const state = {
    count: 0
    }

    // 2. 获取state中的值
    this.$store.state.count

    // mapState 辅助函数获取多个state的值
    import { mapState } from 'vuex'
    computed: mapState({

    // 箭头函数可使代码更简练count: state => state.count,// 传字符串参数 'count' 等同于 `state => state.count`countAlias: 'count',

    })
    computed: mapState([
    // 映射 this.count 为 store.state.count
    'count'
    ])

    // 3. 与组件的计算属性混合使用
    computed: {
    localComputed () { / ... / },
    // 使用对象展开运算符将此对象混入到外部对象中
    ...mapState({

    // ...

    })
    }

mutations

(一个对象,保存的是更改state的函数,也只有它能更改state中的值,触发方式this.$store.commit('函数名',参数))

// 1. 定义const mutations = {  increment (state) {    state.count++  }}// 2. 触发this.$store.commit('increment')// 3. 传递参数,通常参数应该是一个对象mutations: {  increment (state, n) {    state.count += n  }}this.$store.commit('increment', 10)// 4. 在组件的方法中使用  methods: {    ...mapMutations([      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`      // `mapMutations` 也支持载荷:      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`    ]),    ...mapMutations({      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`    })  }

actions

(一个对象,保存的是触发mutations的函数,让mutations去修改state中的值)

// 1. 定义const actions = {  increment: ({ commit }) => commit('increment')}// 2. 触发this.$store.dispatch('increment')// 3. 参数支持this.$store.dispatch('incrementAsync', {  amount: 10})// 4. 组件的方法中使用  methods: {    ...mapActions([      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`      // `mapActions` 也支持载荷:      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`    ]),    ...mapActions({      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`    })  }

getters

(一个对象,保存的是一些类似与计算属性的函数,可以通过他们得到任何依赖于state的新的数据)

// 1. 定义const getters = {  evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'}// 2. 使用this.$store.getters.evenOrOdd// 3. 使用其他getters作为参数getters: {  // ...  doneTodosCount: (state, getters) => {    return getters.doneTodos.length  }}// 4. 组件内使用export default {  // ...  computed: {  // 使用对象展开运算符将 getter 混入 computed 对象中    ...mapGetters([      'doneTodosCount',      'anotherGetter',      // ...    ])  }}

使用vuex

npm install vuex -S

// store.jsimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const state = {}const mutations = {}const actions = {}const getters = {}export default new Vuex.Store({  state,  getters,  actions,  mutations})// app.jsimport store from './store'new Vue({  el: '#app',  store,  render: h => h(Counter)})