Vuex

176 阅读3分钟

Vuex是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。 通俗一点说Vuex就是一个是一个全局模型,目的是为了管理共享状态,以此来达到让项目结构更加清晰且易于维护的目的 

使用 Vuex 并不意味着你需要将所有的状态放入 Vuex。虽然将所有的状态放到 Vuex 会使状态变化更显式和易调试,但也会使代码变得冗长和不直观。如果有些状态严格属于单个组件,最好还是作为组件的局部状态。你应该根据你的应用开发需要进行权衡和确定。

 Vuex和单纯的全局对象有两点不同:

 1.Vuex的状态储存是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生改变,那么响应的组件也会得到高效更新 2.我们不能直接改变store中的状态。改变store中状态的唯一途径就是显示第提交,(commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好的了解我们的应用。


简单实例

// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

每一个Vuex应用的核心就是store(仓库)。store基本上就是一个容器,它包含这我们应用中的大部分的状态(state)


Mutations

store.commit('increment') // 调用 mutations 中的方法
console.log(store.state.count) // -> 1

我们通过提交mutation的方式,而非直接改变store.state.count,是因为我们想要跟明确的

地追踪到状态的变化。这个简单的约定更够让你的意图更加明显,这样你在阅读代码的时候能更容易地解读应用内部的状态改变。此外,这样也让我们有机会去实现一些能记录每次状态改变,保存状态快照的调试工具。有了它,我们甚至可以实现时间穿梭般的调试体验。

由于store中的状态是响应式的,在组件中调用store中的状态简单到仅需要在计算属性中返回即可。触发变化也仅仅实在组件的methods中提交mutation

只有muation可以修改state

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    // 事件类型 type 为 increment
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

注意,我们不能直接 store.mutations.increment() 来调用,Vuex 规定必须使用 store.commit 来触发对应 type 的方法:

store.commit('increment')
传参

我们还可以向 store.commit 传入额外的参数:

mutations: {
  increment (state, n) {
    state.count += n
  }
}

// 调用
store.commit('increment', 10)

Getter

相当于store中的计算属性(computed),getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

简单实例

//eg1:
const store = new Vuex.Store({
  state: {
    date: new Date()
  },
  getters: {
    // Getter 接受 state 作为其第一个参数
    weekDate: state => {
      return moment(state.date).format('dddd'); 
    }
  }
})

//eg:2

getters: {  // Getter 还也可以接收 getters 作为第二个参数
  dateLength: (state, getters) => {
    return getters.weekDate.length;
  }
}

不但如此,Getter 还会将 store.getters 对象暴露出去,你可以以属性的形式访问这些值:

console.log(store.getters.weekDate)

我们可以很容易地在任何组件中使用它:

computed: {
  weekDate () {
    return this.$store.getters.weekDate
  }
}

Getter 传参

因为 Getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的,所以是不能直接 store.getters.weekDate('MM Do YY'),因为 weekDate 并不是一个函数,它仅仅只是一个属性而已,我们就想办法把这个属性变成一个函数。

getters: {
  // 返回一个函数,就可以传参了
  weekDate: (state) => (fm) => {
    return moment(state.date).format(fm ? fm : 'dddd'); 
  }
}

//使用如下
store.getters.weekDate('MM Do YY')


Action

Action 类似于 mutation,不同在于:

1、Action 提交的是 mutation,而不是直接变更状态。
2、Action 可以包含任意异步操作。

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

可以看到,Action 函数接受一个 context 参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性,但是他们并不是同一个实例,后面学习 Modules 的时候会介绍它们为什么不一样。

所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。

action 内部执行异步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

和 Mutation 分发的方式异曲同工,这是注意这里是 dispatch

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

来看一个更加实际的购物车示例,涉及到调用异步 API 和分发多重 mutation:

actions: {
  checkout ({ commit, state }, products) {
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求,然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

辅助函数

mapState

 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态。那么,当一个组件需要获取多个状态的时候,怎么办。这是就用到了mapState

我们可以直接把需要用到的状态全部存放在 mapState 里面进行统一管理,而且还可以取别名,做额外的操作等等

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    a: state => state.a,
    b: state => state.b,
    c: state => state.c,

    // 传字符串参数 'b'
    // 等同于 `state => state.b`
    bAlias: 'b',

    // 为了能够使用 `this` 获取局部状态
    // 必须使用常规函数
    cInfo (state) {
      return state.c + this.info
    }
  })
}

如果所映射的计算属性名称与 state 的子节点名称相同时,我们还可以更加简化,给 mapState 传一个字符串数组:

computed: mapState([
  // 映射 this.a 为 store.state.a
  'a',
  'b',
  'c'
])

因为 computed 这个计算属性接收的是一个对象,所以由上面的示例代码可以看出,mapState 函数返回的是一个对象,现在如果想要和局部的计算属性混合使用的话,可以使用 ES6 的语法这样写来大大简化:

computed: {
  localComputed () { 
    ...
  },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}

mapGetters

这个和 mapState 基本上没啥区别,简单看下官方的例子,就懂了:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

取个别名,那就用对象的形式,以下示例的意思就是把 this.doneCount 映射为 this.$store.getters.doneTodosCount

mapGetters({
  doneCount: 'doneTodosCount'
})

mapMutations

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      // 将 `this.increment()` 映射为 
      // `this.$store.commit('increment')`
      'increment', 
      // `mapMutations` 也支持载荷:
      // 将 `this.incrementBy(amount)` 映射为 
      // `this.$store.commit('incrementBy', amount)`
      'incrementBy' 
    ]),
    ...mapMutations({
      // 将 `this.add()` 映射为 
      // `this.$store.commit('increment')`
      add: 'increment' 
    })
  }
}

mapActions

mapMutations 用法一模一样,换个名字即可。

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      // 将 `this.increment()` 映射为 
      // `this.$store. dispatch('increment')`
      'increment', 
      // `mapActions` 也支持载荷:
      // 将 `this.incrementBy(amount)` 映射为 
      // `this.$store. dispatch('incrementBy', amount)`
      'incrementBy' 
    ]),
    ...mapActions({
      // 将 `this.add()` 映射为 
      // `this.$store. dispatch('increment')`
      add: 'increment' 
    })
  }
}

想要在组件中调用,直接 this.xxx 就完了。