Vuex3.x、Vuex4.x状态管理器学习笔记

Vuex使用记录

1.在Vue2.x中使用

import Vuex from 'vuex'  /* 引入Vuex  */
Vue.use(Vuex)  /* 安装插件 */
/* 实例化Vuex */
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
/* 挂载到所有组件 */
new Vue({
  el: '#app',
  store: store,
})

2.在Vue3.x中使用

import { createApp } from 'vue'
import { createStore } from 'vuex'
/* 创建一个新的 store 实例 */
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
const app = createApp({ /* 根组件 */ })
/* 将 store 实例作为插件安装 */
app.use(store)

3.辅助函数

mapState、mapGetters、mapActions、mapMutations

  ...mapActions([
    'some/nested/module/foo',  /* -> this['some/nested/module/foo']()*/
    'some/nested/module/bar'   /*-> this['some/nested/module/bar']()*/
  ])
/* 可以在第一个参数中传递模块名,简写 */
...mapActions('some/nested/module', [
    'foo', /* -> this.foo() */
    'bar' /* -> this.bar()*/
  ])

4.学习

  1. Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT)”而存在。
  2. Vuex的对象可以用过use注入vue应用,成为所有组件的store属性。也可以单独引入这个对象,单独使用。
  3. Vuex的所有方法中,this指向Vuex对象。

5.state(状态/数据)

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

6.getter(state的计算属性?)

getters: {
    doneTodos: (state) => {
      return state.todos.filter(todo => todo.done)
    }
  }

7.mutation(事件,由commit触发)

store.commit('increment')
...mapMutations({
    add: 'increment' /*将 `this.add()` 映射为 `this.$store.commit('increment')`*/
})

8.action(异步处理状态,由dispatch触发)

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
/* 参数解构 */
actions: {
    checkout ({ commit, state }, products) {
    }
}

9.模块分割 Module

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}
const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}
const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
store.state.a /* -> moduleA 的状态 */
store.state.b /* -> moduleB 的状态 */

10.项目结构说明

11.组合式API使用

this.$store

12.订阅

订阅 store 的 mutation。handler 会在每个 mutation 完成后调用,接收 mutation 和经过 mutation 后的状态作为参数

订阅 store 的 action。handler 会在每个 action 分发的时候调用并接收 action 描述和当前的 store 的 state 这两个参数。 subscribe 方法将返回一个 unsubscribe 函数,当不再需要订阅时,应调用该函数。