vuex

1,669 阅读4分钟

总结官方文档中的内容,方便自己看

介绍

专为vue.js开发的状态管理模式,把不同组件的共享状态抽取出来,以一个全局单例模式管理
npm
npm install vuex --save
安装

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

store(仓库)
基本就是一个容器,它包含着你的应用中大部分的状态(state)。
vuex和单纯的全局对象有以下两点不同:
1.Vuex的状态存储是响应式的。store中的状态改变,组件中也会更新。
2.不能直接改变store中的状态。【应该提交mutation】
创建Store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

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

使用 store.state 获取状态对象,通过 store.commit方法触发状态变更

store.commit('increment')
console.log(store.state.count) // -> 1

为了在Vue组件中访问 this.$store property,需要为Vue实例提供创建好的store,需要在根组件注入store机制:

new Vue({
  el: '#app',
  store: store,
})

然后可以从组件的方法提交一个变更:

methods: {
  increment() {
    this.$store.commit('increment')
    console.log(this.$store.state.count)
  }
}

核心概念

State


单一状态树,用一个对象就包含了全部的应用层级状态,每当 ` store.state.count ` 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

mapState 辅助函数

当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些复杂和冗余,这时可以使用mapState辅助函数帮助生成计算属性,可以帮助我们少按几次键

import { mapState } from "vuex";
computed: {
    // 使用对象展开运算符将此对象混入到外部对象中
    ...mapState(["count", "data01"]),
    }
//使用
console.log("count", this.count);

Getters

vueX允许我们在store中定义“getter”(可以认为是store中的计算属性)。有缓存,只有依赖值发生变化才会重新计算

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
  }
}

通过方法访问
可以通过让 getter 返回一个函数,来实现给 getter 传参。

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([
      "doneTodos",
      "doneTodosCount",
      // ...
    ])
  }
}
 //使用时
 console.log("getter", this.doneTodos);

如果你想将一个 getter 属性另取一个名字,使用对象形式:

...mapGetters({
  //`this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

Mutations

更改Vuex的store中的状态的唯一方法是提交mutation。【提交mutation可以方便管理,直接修改state中的状态过于分散,不好管理】

store中mutation进行修改状态

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

组件中调用 store.coommit 方法:

store.commit('increment')

提交载荷(Payload)

你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

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

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

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}

3.Mutation必须是同步函数

在组件中提交 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')`
    })
  }
}

Mutation都是同步事务 处理异步操作看Action

Actions

Action函数接受一个与store实例具有相同方法和属性的context对象,因此你可以调用context.commit提交一个mutation,或者通过context.state和context.getters来获取state和getters。
Actions类似于mutation,不同在于:

  1. Action提交的是mutation,而不是直接变更状态。
  2. Action可以包含任意异步操作
    分发Action
    Action通过store.dispatch方法触发
store.dispatch('increment')
// 以载荷形式分发
store.dispath('incrementAsync',{
   amount: 10
   })
// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
//可以在action内部执行异步操作
action: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

在组件中分发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:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

现在可以:

store.dispatch('actionA').then(() => {
  // ...
})

在另外一个 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最后,如果我们利用 async / await (opens new window),我们可以如下组合 action:

// 假设 getData() 和 getOtherData() 返回的是 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

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,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 的状态

项目结构