Vue核心插件之Vuex

简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,统一存储管理和维护所有组件的可变化状态。
应用背景:

  • 多层嵌套的组件或者兄弟组件需要共享同一状态
  • 多层嵌套的组件或者兄弟组件通讯,需要变更状态
  • 如果应用够简单,不建议使用vuex, 一个简单的store 模式就能满足所需;如果构建一个中大型单页应用,想要更好地在组件外部管理状态,Vuex 将会成为自然而然的选择.
    Vue核心插件之Vuex_第1张图片

核心概念

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

  • vuex的状态存储是响应式的.当 Vue 组件从 store 中读取状态的时候,若 store中的状态发生变化,那么相应的组件也会相应地得到高效更新。

  • 不能直接更改store中的状态. 改变store中状态的唯一途径就是显式地提交 (commit)mutation
    如下:

    // 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
    import Vue from 'vue'
    import Vuex from 'vuex'
    import createLogger from 'vuex/dist/logger'
    // 使用插件
    Vue.use(Vuex)
    export default new Vuex.Store({
           
      state: {
           
        count: 0
      },
      mutations: {
           
        increment (state) {
           
          state.count++
        }
      }
      // 打印日志观察流程
      plugins: process.env.NODE_ENV !== 'production' ? [createLogger()] : []
    })
    
    // 变更状态
    store.commit('increment')
    // 查询状态
    console.log(store.state.count) // -> 1
    

Vue核心插件之Vuex_第2张图片

State

Vuex 使用单一状态树,即用一个对象就包含了全部的应用层级状态.

  • 获取状态:
  1. Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):

    import Vue from 'vue'
    import App from './App'
    // store
    import store from '@/store/index'
    // 菜单和路由设置
    import router from './router'
    new Vue({
           
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
    // 查询状态
     this.$store.state.count
    
  2. 获取状态
    通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到

    computed: {
           
      count () {
           
        return this.$store.state.count
      }
    }
    
  • mapState 辅助函数
    当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余, 使用 mapState 函数帮助我们生成计算属性.
    mapState 函数返回的是一个对象。我们需要使用工具函数(对象展开运算符)将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性.
    import {
            mapState } from 'vuex'
    computed: {
           
      // 使用对象展开运算符将此对象混入到外部对象中
      ...mapState({
           
       // ...
      }),
      localComputed () {
            /* ... */ },
    }
    

Getter

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:

computed: {
     
  doneTodosCount () {
     
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:

const store = new Vuex.Store({
     
  state: {
     
    todos: [
      {
      id: 1, text: '...', done: true },
      {
      id: 2, text: '...', done: false }
    ]
  },
  getters: {
     
    doneTodos: state => {
     
      return state.todos.filter(todo => todo.done)
    }
  }
})
  • 通过属性访问
    Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值:

    store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
    // Getter 也可以接受其他 getter 作为第二个参数:
    getters: {
           
     // ...
      doneTodosCount: (state, getters) => {
           
        return getters.doneTodos.length
      }
    }
    // 访问
    computed: {
           
      doneTodosCount () {
           
        return this.$store.getters.doneTodosCount
     }
    }
    

    注意: getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

  • 通过方法访问
    也可通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用

    getters: {
           
      // ...
      getTodoById: (state) => (id) => {
           
        return state.todos.find(todo => todo.id === id)
      }
    }
    // 访问
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    注意: getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

  • mapGetters 辅助函数
    mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

    import {
            mapGetters } from 'vuex'
    
    export default {
           
      computed: {
           
        // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter'
        ])
      }
    }
    // 如果你想将一个 getter 属性另取一个名字,使用对象形式:
    mapGetters({
           
     // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
    })
    

Mutation

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

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

你不能直接调用一个 mutation handler。“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法

store.commit('increment')
  • 提交载荷(Payload)
    向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)
    在大多数情况下,载荷应该是一个对象,这样可以包含多个字段:

    mutations: {
           
     increment (state, payload) {
           
       state.count += payload.amount
     }
    }
    store.commit('increment',  {
           amount: 10})
    

    提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

    store.commit({
           type: 'increment', amount: 10})
    mutations: {
           
     increment (state, payload) {
           
       state.count += payload.amount
     }
    }
    
  • Mutation 需遵守 Vue 的响应规则

    1.提前在 store 中初始化好所有所需属性

    2.当需要在对象上添加新属性时,你应该:

     // 新增
     Vue.set(obj, 'newProp', 123),
     // 替换(利用对象展开运算符)
     state.obj = {
            ...state.obj, newProp: 123 }
    
  • 使用常量替代 Mutation 事件类型

    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    
    import Vuex from 'vuex'
    import {
            SOME_MUTATION } from './mutation-types'
    
    const store = new Vuex.Store({
           
      state: {
            ... },
      mutations: {
           
        // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
        [SOME_MUTATION] (state) {
           
         // mutate state
        }
      }
    })
    
  • 在组件中提交 Mutation
    你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

    import {
            mapMutations } from 'vuex'
    
    export default {
           
      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')`
        })
      }
    }
    

Action

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

const store = new Vuex.Store({
     
  state: {
     
    count: 0
  },
  mutations: {
     
    increment (state) {
     
      state.count++
    }
  },
  actions: {
     
    //increment (context) {
     
      //context.commit('increment')
   // }
   // es6的参数解构简化代码
   increment ({
      commit }) {
     
     commit('increment')
   }
  }
})

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象, 可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。可用es6的参数解构简化代码

  • 触发Action
    Action 通过 store.dispatch 方法触发:

    store.dispatch('increment')
    actions: {
           
      incrementAsync ({
            commit }) {
           
         // 异步操作
        setTimeout(() => {
           
          commit('increment')
        }, 1000)
      }
    }
    

    Actions 与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)
        )
      }
    }
    

    注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)

  • 在组件中分发 Action
    在组件中使用 this.$store.dispatch(‘xxx’) 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

    import {
            mapActions } from 'vuex'
    export default {
           
      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')`
       })
      }
    }
    
  • 组合Action

    Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

    首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

     // 假设 getData() 和 getOtherData() 返回的是 Promise
     // async await 是promise的语法糖
    actions: {
           
      async actionA ({
            commit }) {
           
        commit('gotData', await getData())
      },
      async actionB ({
            dispatch, commit }) {
           
        await dispatch('actionA') // 等待 actionA 完成
        commit('gotOtherData', await getOtherData())
      }
    }
    

    一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

Module

当应用比较复杂, 所有状态会集中成较大的对象时,Vuex 允许将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
     
  state: {
      ... },
  mutations: {
      ... },
  actions: {
      ... },
  getters: {
      ... }
}

const moduleB = {
     
  state: {
      ... },
  mutations: {
      ... },
  actions: {
      ... }
}

const store = new Vuex.Store({
     
  modules: {
     
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

更多详情…

Vuex 规则

  • 应用层级的状态应该集中到单个 store 对象中
  • 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的
  • 异步逻辑都应该封装到 action 里面

参考实例

购物车实例

你可能感兴趣的:(VUE,vue,vue.js,前端)