​ Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。


工作原理

markdown picture

state :存储用于vuex全局共享的数据

Actions : 用于响应组件中的动作

Mutations : 用于操作state中的数据

​ Vue组件通过Dispath()将操作与参数传给actions,actions根据对应的操作将其commit给mutations,mutations执行操作修改state中的值,而vue组件可以通过render获取到state中的全局变量。


搭建Vuex环境

搭建store

​ 在/项目目录/src路径下创建store文件夹,里面创建index.js文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {}
const mutations = {}
const state = {}

export default new Vuex.Store({
actions,
mutations,
state
})

​ 在main.js下引入store:

1
2
3
4
5
6
7
8
9
10
11
12
13
import App from './App.vue'
import Vue from 'vue'
+ import store from './store'

Vue.config.productionTip = false
new Vue({
el: "#app",
render: h => h(App),
+ store,
beforeCreate() {
Vue.prototype.$bus = this
},
})

​ 这样即可在任意组件下使用$store,与Vuex进行对话


Vuex五大状态

State

​ 提供唯一的公共数据源,所有共享的数据统一放到store的state进行存储,相似于data

​ 在vuex中state定义的数据可以在任意组件中使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {}
const mutations = {}
//数据,相当于data
const state = {
name: "张三",
age: 12,
count: 0
}

export default new Vuex.Store({
actions,
mutations,
state
})

调用方法

在标签中直接使用

1
2
<p>{{$store.state.变量1}}</p>
<p>{{$store.state.变量2}}</p>

script中用this调用

1
this.$store.state.全局变量名称

mapState函数

​ 引入mapState函数:

1
import {mapState} from "vuex"

​ 在当前组件的computed属性中调用mapState:

1
2
3
computed: {
...mapState(["变量1","变量2","变量3"])
}

​ 使用方法:

1
2
3
<p>{{$store.state.变量1}}</p>
<p>{{$store.state.变量2}}</p>
<p>辅助函数mapState{{变量1+变量2+变量3}}</p>

Mutation

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

在vuex中定义

其中参数state参数是必须的,也可以自己传递一个参数,如下代码,进行计数器的加减操作,加法操作时可以根据所传递参数大小进行相加,减法操作没有传参每次减一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
state: {
name: "张三",
age: 12,
count: 0
}
//里面定义方法,操作state的变量值
mutations: {
addCount(state,num){
state.count=state.count+num
},
reduce(state){
state.count--
}
}

在组件中使用

1
2
<button @click="btn">点我增加store仓库中的数据</button>
<button @click="btn1">点我减少store仓库中的数据</button>

方法一:commit

使用commit触发Mutation操作

1
2
3
4
5
6
7
8
9
10
methods: {
//加法
btn(){
this.$store.commit("addcount",10)
}
//减法
btn1(){
this.$store.commit("reduce")
}
}

方法二:mapMutations

使用辅助函数进行操作

1
2
3
4
5
6
7
8
9
methods: {
...mapMutations(["addcount","reduce"]),
btn(){
this.addcount(10);
},
btn1(){
this.reduce();
}
}

Action ——进行异步操作

Action和Mutation相似,一般不用Mutation 异步操作,若要进行异步操作,使用Action的原因:为了方便devtools打个快照存下来,方便管理维护。所以说这个只是规范,而不是逻辑的不允许,只是为了让这个工具能够追踪数据变化而已

在vue中定义

将上面的减法操作改为异步操作

1
2
3
4
5
6
7
8
9
//操作异步操作mutation
actions: {
asyncAdd(context){
//异步
setTimeout(()=>{
context.commit("reduce")
},1000);
}
},

在组件中使用

方法一:直接使用dispatch

1
this.$store.dispatch("asynAdd")

方法二:使用辅助函数

1
2
3
4
...mapActions(["asyncAdd"]),
btn2(){
this.asyncAdd()
}

Getter

类似于vue中的computed,对State中的数据进行加工处理形成新数据

Modules

当遇见大型项目时,数据量大,store就会显得很臃肿

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
modules: {
cityModules: {
namespaced: true,
state: {
cityName: "长沙"
},
mutations:{
cityFuntion(state){
state.cityName="开封"
}
}
},
userinfo: {
state: {
username: "张三",
}
}
}

​ 默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间的——这样使得多个模块能够对同一个 action 或 mutation 作出响应。

​ 如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名

1
2
3
btn3(){
console.log(this.$store.state.cityMoudles.cityName);
}

附录

参考文章:

Mr.指尖舞者——Vuex详解,一文彻底搞懂Vuex