vuex的认识
一、vuex的简介
1.1 什么是vuex?
参考文档:https://vuex.vuejs.org/zh/guide/actions.html
官方解释:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
总结:
- vuex 是专门用来管理 vue.js 应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在一起,集中式来管理。
- 需要声明的是,这里所说的状态指的是 vue 组件中 data 里面的属性
- 其实简单的理解为将其看成把需要多个组件共享的变量全部存储在一个对象里面。
- 然后,将这个对象放在顶层的 Vue 实例中,让其他组件可以共享,(类似于 java 中的 static 关键字修饰的变量,可以共享),而vuex里边定义的状态是响应式的。
- 当在多个组件之间需要共享的状态、组件之间层级结构比较复杂,而且需要共享状态,就把这些状态放到 vuex 中。
1.2 什么是“状态管理模式” ?
下面介绍一个简单地 vue 计数实例
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
我们知道,在单个组件中进行状态管理是一件非常简单的事情,接下来我们看下边的图片:
图片上边的三种东西怎么理解呢?
State:驱动应用的数据源;就是所谓的状态,姑且可以理解为组件 data 中的属性
View:以声明的方式将 state 映射到视图;其实就是视图层,可以针对 state 的变化,显示不同的信息(响应式)
Action:响应在 view 上的用户输入导致的状态变化;主要是用户的各种操作:点击、输入等等,会导致状态的改变
这个只是针对单个组件中进行状态管理,当我们应用到多个组件共享状态(Vue 组件中的 data 属性)时,单向数据流的简洁很容易被破坏:
- 多个组件之间依赖于同一状态。
- 来自不同组件的行为需要变更同一状态。
对于问题一:传参(props等)的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
对于问题二:我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码
因此,我们把组件的共享状态抽取出来,以一个全局单例模式管理(就是所谓的vuex),可以理解为java中的单例模式,所有组件共享这个状态。
二、vuex的组成结构示意图
vuex的特点是把数据单独隔离,形成一棵树状图。单独隔离就意味着它有自己的生态系统。输入和输出,其中action作为数据的输入,state作为数据的输出。如下图:
vuex里有这么一个规则:
- 只能在 mutaions 里修改 state,actions 不能直接修改 state,
- 因为 vue 官方为我们提供了一个插件,叫做 Devtools (浏览器插件),如上图所示,它的作用是可以记录每次 state 修改后的状态,但是只有通过 mutations 修改的 state,才会帮我们记录,所以修改state时,建议使用 mutaions 修改,这样方便我们进行程序调试。
- mutations 变化,修改 state 的数据,而且只能是同步的,做同步操作时可以跳过 actions,在 mutations 里不能存在异步的操作。
- 如果需要异步怎么办呢?把异步操作放在 actions 里,拿到数据再通过 mutations 同步处理。
vuex 做的其实是把职权明确了,责任细分了。所以它文档里也说,小系统可以不用。状态数据少,没有细分的必要。通过这个图,我们很容易就对 vuex 的组成部分,以及 vuex 与组件 (components) 之间的联系一目了然。
三、安装vuex
这里推荐使用NPM的方式进行安装
npm install vuex --save
四、vuex初体验
4.1 创建项目
首先使用vue-cli2(这里使用cli2) 进行创建项目,并新建一个文件夹 命名为 store ,在 store 中创建 index.js 文件
4.2 实例化 store 对象
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
1.Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化(Devtools 工具),从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
语法:
代码演示
index.js
//index.js
import Vue from 'vue';
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex) //会去执行Vuex.install
//2.创建对象
const store = new Vuex.Store({
state:{
// 存放状态
},
getters:{
// state的计算属性
},
mutations:{
// 更改state中状态的逻辑,同步操作
},
actions:{
// 提交mutation,异步操作
},
// 如果将store分成一个个的模块的话,则需要用到modules。
//然后在每一个module中写state, getters, mutations, actions等。
modules:{
a: moduleA,
b: moduleB,
// ...
}
})
//3.导出store对象
export default store
main.js
//main.js
import Vue from 'vue'
import App from './App'
import store from "./store";
Vue.config.productionTip = false
/* eslint-disable no-new */
//在vue实例中进行挂载
new Vue({
el: '#app',
store,
render: h => h(App)
})
五、vuex的核心概念
5.1 state
state上存放的,说的简单一些就是变量,也就是所谓的状态。没有使用 state 的时候,我们都是直接在 data 中进行初始化的,但是有了 state 之后,我们就把 data 上的数据转移到 state 上去了。另外有些状态是组件私有的状态,称为组件的局部状态,我们不需要把这部分状态放在store中去。
单一状态树:
Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态,作为唯一数据源而存在,意思每个应用将仅仅包含一个 store 实例,把这个 store 作为唯一的数据来源,这样方便进行管理和维护。
5.1.1 如何在组件中获取vuex状态
由于vuex的状态是响应式的,所以从store中读取状态的的方法是在组件的计算属性中返回某个状态。
import store from 'store';
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
// 获取store中的状态
return store.state.count;
}
}
}
这样,组件中的状态就与store中的状态关联起来了。每当store.state.count发生变化时,都会重新求取计算属性,从而更新DOM。
然而,每个组件中都需要反复倒入store。可以将store注入到vue实例对象中去,这样每一个子组件中都可以直接获取store中的状态,而不需要反复的倒入store了。
const app = new Vue({
el: '#app',
// 把 store 对象注入到了
store,
components: { Counter },
template: `
<div>
<counter></counter>
</div>
`
});
这样可以在子组件中使用this.$store.state.count访问到state里面的count这个状态
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
// 获取store中的状态
return this.$store.state.count;
}
}
}
5.1.2 mapState
当一个组件获取多种状态的时候,则在计算属性中要写多个函数。为了方便,可以使用mapState辅助函数来帮我们生成计算属性。
import { mapState } from 'vuex';
export default {
// ...
data (){
localState: 1
}
computed: mapState({
// 此处的state即为store里面的state
count: state => state.count,
// 当计算属性的名称与state的状态名称一样时,可以省写
// 映射 this.count1 为 store.state.count1
count1,
//'count'等同于 ‘state => state.count’
countAlias: 'count',
countPlus (state){
// 使用普通函数是为了保证this指向组件对象
return state.count + this.localState;
}
})
}
//上面是通过mapState的对象来赋值的,还可以通过mapState的数组来赋值
computed: mapState(['count']);
//这种方式很简洁,但是组件中的state的名称就跟store中映射过来的同名
5.1.3 对象扩展运算符
mapState 函数返回的是一个对象,为了将它里面的计算属性与组件本身的局部计算属性组合起来,需要用到对象扩展运算符。
computed: {
localState () {
... mapState ({
})
}
这样,mapState中的计算属性就与localState计算属性混合一起了。
5.2 getters
在实际开发中,有时候不仅仅需要单一的展示我们的数据,当我们希望我们的数据发生一些变化时,然后在展示在页面上,那么现在就用到了计算属性。
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数。此时可以用到getters,getters可以看作是store的计算属性,其参数为state。
const store = new Vuex.Store({
state: {
todos: [
{id: 1, text: 'reading', done: true},
{id: 2, text: 'playBastketball', done: false}
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done);
}
}
});
代码演示
定义一个学生数组,然后获取学生中年龄大于二十的学生
const store = new Vuex.Store({
state:{
//定义一个学生数组
students:[
{id:110,name:'zhangsan',age:18},
{id:111,name:'lisi',age:19},
{id:112,name:'wangwu',age:38},
{id:113,name:'zhaoliu',age:26},
]
},
getters:{
//获取学生中年龄大于二十岁的学生
moreStu(state){
return state.students.filter(s => s.age > 20)
}
}
})
Getter 也可以接受其他 getter 作为第二个参数:
例如:获取学生中年龄大于二十的学生的个数
const store = new Vuex.Store({
state:{
students:[
{id:110,name:'zhangsan',age:18},
{id:111,name:'lisi',age:19},
{id:112,name:'wangwu',age:38},
{id:113,name:'zhaoliu',age:26},
]
},
getters:{
moreStu(state){
return state.students.filter(s => s.age > 20)
},
// 这里的 getter 就代表上边的 getters
moreStuLength(state,getter){
return getter.length
}
},
})
当我们需要向 Getter 中传入一个我们自己定义的变量,应该怎么办呢?
例如:获取学生中年龄大于age(这里的 age 是一个变量,需要调用者传入)的学生
const store = new Vuex.Store({
state:{
students:[
{id:110,name:'zhangsan',age:18},
{id:111,name:'lisi',age:19},
{id:112,name:'wangwu',age:38},
{id:113,name:'zhaoliu',age:26},
]
},
getters:{
moreStu(state){
return state.students.filter(s => s.age > 20)
},
// 这里的 getter 就代表上边的 getters
moreStuLength(state,getter){
return getter.length
},
moreAgeStu(state){
return function (age) {
return state.students.filter(s => s.age > age)
}
}
},
})
5.3 mutations
5.3.1 mutations的语法
更改 Vuex 的 store 中的状态的唯一方法:是提交 mutation,即store.commit(‘increment’)。
Vuex 中的 mutation 非常类似于事件:
- 每个 mutation 都有一个字符串的事件类型 (type) 和 一个 回调函数 (handler)。
- 这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
mutation的定义方式:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
通过mutation更新
increment:function(){
this.$store.commit('increment')
}
5.3.2 提交载荷(Payload)
你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
在大多数情况下,payload 应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
提交 mutation 的另一种方式是直接使用包含 type 属性的对象
store.commit({
type: 'increment',
amount: 10
});
// mutations保持不变
mutations: {
increment(state, payload){
state.count += payload.amount;
}
}
5.3.3 Mutation 需遵守 Vue 的响应规则
既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
最好提前在你的 store 中初始化好所有所需属性
当需要在对象上添加新属性时,你应该
2.1 使用 Vue.set(obj, ‘newProp’, 123)
2.2 或者以新对象替换老对象
5.3.4 使用常量替代 Mutation 事件类型
- 在 mutations 中,我们定义了很多事件类型(也就是其中的方法名称)
- 当我们的项目增大时,Vuex 管理的状态越来越多,需要更新状态的情况越来越多,那么意味着 Mutation 中的方法越来越多。
- 方法过多,使用者需要花费大量的精力去记住这些方法,甚至是多个文件之间来回切换,查看方法的名称,这样很容易出错。
- 这时就需要常量来代替 Mutation 的事件类型
mutation-types.js
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
store.js
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
5.4 actions
因为mutations中只能是同步操作,但是在实际的项目中,会有异步操作,那么actions就是为了异步操作而设置的。这样,就变成了在action中去提交mutation,然后在组件的methods中去提交action。只是提交actions的时候使用的是dispatch函数,而mutations则是用commit函数。
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
一个简单地 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
//类似于store
increment (context) {
context.commit('increment')
}
}
})
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters
5.4.1 在组件中分发action
方法1: 在组件的methods中,使用this.$store.dispatch(‘increment’)。
方法2: 使用mapActions,跟mapMutations是类似的。
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
]),
...mapActions({
add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
})
}
}
// 同样在组件中,可以这样来使用
<button @click="increment">+</button>
5.4.2 组合actions
因为action是异步的,那么我们需要知道这个异步函数什么时候结束,以及等到其执行后,会利用某个action的结果。这个可以使用promise来实现。在一个action中返回一个promise,然后使用then()回调函数来处理这个action返回的结果。
actions:{
actionA({commit}){
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation');
resolve();
},1000);
})
}
}
// 这样就可以操作actionA返回的结果了
store.dispatch('actionA').then(() => {
// dosomething ...
});
// 也可以在另一个action中使用actionA的结果
actions: {
// ...
actionB({ dispatch, commit }){
return dispatch('actionA').then(() => {
commit('someOtherMutation');
})
}
}
5.5 mudules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
module是为了将store拆分后的一个个小模块,这么做的目的是因为当store很大的时候,分成模块的话,方便管理。
5.5.1 每个module拥有自己的state, getters, mutation, action
const moduleA = {
state: {...},
getters: {...},
mutations: {....},
actions: {...}
}
const moduleB = {
state: {...},
getters: {...},
mutations: {....},
actions: {...}
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
});
store.state.a // 获取moduleA的状态
store.state.b // 获取moduleB的状态
5.5.2 模块中的getters
import Vue from 'vue';
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex) //会去执行Vuex.install
//定义了一个模块 moduleA
const moduleA = {
state:{
name:'zhangsan'
},
getters:{
fullname(state){
return state.name + '111'
},
//此处的 getter 代表 moduleA 中的 getters
fullname2(state,getter){
return getter.fullname + '222'
},
//此处的 rootState 代表 store 中的 state
fullname3(state,getter,rootState){
return getter.fullname2 + rootState.counter
}
}
}
//2.创建对象
const store = new Vuex.Store({
state:{
counter:100,
students:[
{id:110,name:'zhangsan',age:18},
{id:111,name:'lisi',age:19},
{id:112,name:'wangwu',age:38},
{id:113,name:'zhaoliu',age:26},
]
},
getters:{
powerCounter(state){
return state.counter * state.counter
},
moreStu(state){
return state.students.filter(s => s.age > 20)
},
// 这里的 getter 就代表上边的 getters
moreStuLength(state,getter){
return getter.length
},
moreAgeStu(state){
return function (age) {
return state.students.filter(s => s.age > age)
}
}
},
modules:{
a:moduleA
}
})
//3.导出store对象
export default store
5.5.3 模块内部的状态
对于模块内部的mutation和getter,接受的第一个参数是模块的局部状态state。顺便说一下,根结点的状态为rootState。
const moduleA = {
state: { count: 0},
getters: {
doubleCount(state){
return state.count * 2;
}
},
mutations: {
increment(state){
state.count ++ ;
}
},
actions: {...}
}
5.5.4 模块的动态注册
在模块创建之后,可以使用store.registerModule方法来注册模块。
store.registerModule('myModule', {
// ...
});
依然的,可以通过store.state.myModule来获取模块的状态。
可以使用store.unregisterModule(moduleName)来动态的卸载模块,但是这种方法对于静态模块是无效的(即在创建store时声明的模块)。