什么是Vuex

  • Vuex是专门为Vue.js设计的状态管理库
  • Vuex采用集中式的方式存储需要共享的状态
  • Vuex的作用是进行状态管理,解决复杂组件通信,数据共享
  • Vuex集成到了devtools,提供了time-travel时光旅行历史回滚功能

什么情况下使用Vuex

  • 非必要的情况不要使用Vuex
  • 大型单页应用程序
    • 多个视图依赖同一个状态
    • 来自不同视图的行为需要变更同一状态

      Vuex核心概念

      Store
      State:状态,保存在store中
      Getter: Vue中的计算属性
      Mutation: 状态变化,需要commit mutation
      Action: 先发异步请求,然后通过Mutation commit状态
      Module: 模块,每个模块都有自己的State/Getter/Mutation/Action

mapState: 获取到state

  1. computed: {
  2. //...mapState(["count"]),
  3. ...mapState({num:"count"})
  4. }

getter

  1. new Vuex.store({
  2. state: {
  3. count: 0
  4. },
  5. getters: {
  6. reverseCount(state){
  7. return state.count++;
  8. }
  9. }
  10. });
  11. //$store.getters.reverseCount

mapGetters

  1. computed: {
  2. ...mapGetters(["count"])
  3. }

mutations

  1. mutations:{
  2. increate(state,payload) {
  3. state.count += payload
  4. }
  5. }
  6. //$store.commit("increate", 2)

mapMutations

  1. methods:{
  2. ...mapMutations(["increate"])
  3. }

actions

  1. increateAsync (context,payload) {
  2. setTimeout(() => {
  3. context.commit("increate",payload)
  4. },2000);
  5. }
  6. //$store.dispatch("increateAsync", 5)

mapActions

  1. methods:{
  2. ...mapActions(["increateAsync"])
  3. }

modules模块
每个模块都有自己的state/getter/mutations…
还可以给模块添加nameSpaced

Plugin

  1. const myPlugin = store => {
  2. store.subscribe((mutation, state) => {
  3. if(mutation.type.startsWith("cart/")) {
  4. window.localStorage.setItem("cart-products", JSON.stringify(state.cart.cartProducts))
  5. }
  6. })
  7. }
  8. new Vuex.store({
  9. state: {
  10. count: 0
  11. },
  12. plugins: [myPlugin]
  13. });