前言
复杂组件间的通信让人头疼,于是产生了一个公共的管理数据的库 - Vuex
VueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。
五大核心概念
state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,异步!
modules => 模块化Vuex
State
const store = new Vuex.Store({
state: {
count:0 //定义的数据
}
})
const app = new Vue({
store,
computed: {
count: function(){
return this.$store.state.count
}
}
})
每当 store.state.count
变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
getters
对state属性进行计算,可以理解类似于Vue中computed。
store.js中
getters : {
getNum (state) {
return state.num
},
getCount (state) {
return state.count
}
}
vue中
computed: {
count () {
return this.$store.getters.getCount
}
},
this.$store.getters.getCount
来引用数据
mapGetters 辅助函数
//引入
import { mapGetters } from 'Vuex'
//vue
computed: {
...mapGetters(['getCount'])
},
mutations
提交mutation是更改Vuex中的store中的状态的唯一方法。
mutation必须是同步的,如果要异步需要使用action。
定义mutation
// 代码片段
mutations: {
//无提交荷载
addFunc(state) {
state.count++
}
//提交荷载
addFunc(state, obj) {
state.count += obj.n
}
}
触发mutations
//.vue代码片段 main.js引入了store直接使用就好了
method:{
方法名(){
this.$store.commit('addFunc',{ n : 2 }) //提交载荷为例
}
}
Mutation 通过 this.$store.commit
方法触发
actions
类似于 mutation,不同在于:
1. 提交的是 mutation,而不是直接变更状态。
2. 可以包含任意异步操作。
actions: { //注册actions 类似于vue里面的method
increment (context) { // 接收对象context
setInterval(function(){ // 异步中执行
context.commit('addFunc') // 派发给mutation 执行其中的addFunc
}, 1000)
}
}
Action 通过 this.$store.dispatch
方法触发
Modules
使用单一状态树,导致应用的所有状态集中到一个很大的对象。但是,当应用变得很大时,store 对象会变得臃肿不堪。
为了解决以上问题,Vuex 允许我们将 store 分割到模块(module)。每个模块拥有自己的 state、mutation、action、getters、甚至是嵌套子模块——从上至下进行类似的分割:
const mA = {
state : {
a : 1,
b : 1,
},
// 模块的局部 mutations
mutations : {
add : state =>{
state.a++
},
},
getters : {
double : state=> {
return state.a *2
}
}
}
const mB = {
state : {
a : 2,
b : 2,
},
// 模块的局部 mutations
mutations: {
addB: state => {
state.a++
},
},
// 模块的局部 actions
actions : {
asyncAdd : ({commit, rootState ,state}) =>{
setTimeout(() => {
commit('add');
}, 1000);
}
}
}
// store 引入模块
const store = new Vuex.Store({
modules : {
a : mA,
b : mB,
}
});
// 可以拿到对应模块的state
console.log(store.state.a);
(1) 在vue调用
this.$store.commit('mA/add')
(2) 在js调用
store.commit('mA/add')
总结
Vuex有五个核心概念:
- state:vuex的基本数据,用来存储变量
- geeter:从基本数据(state)派生的数据,相当于state的计算属性
- mutation:提交更新数据的方法,必须是同步的
- action:可以包含任意异步操作,处理的事件也要交给mutation
- modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。