一、vuex是什么
Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式发生变化。可以理解为:将多个组件共享的变量全部存储在一个对象里面,然后将这个对象放在顶层的 Vue 实例中,让其他组件可以使用,它最大的特点是响应式。
二、vuex图解
三、vuex的模块
1.state
单一状态树即单一数据源,在一个项目中只使用一个store对象,来存储所有共享的状态信息。
state:{
cartNum:10
}
2.getters
类似于计算属性,在数据展示前进行一些变化处理,具有缓存功能,能够提高运行效率
getters:{
fee(state){ return state.price*0.5}
}
3.mutations
mutations在处理异步操作时,能够引起页面的响应式变化,是改变state的唯一方式
mutations:{
SET_CARTNUM(state,data){
state.cartNum = data;
}
}
4.actions
如果确实需要进行一些异步操作,比如网络请求,建议在 Actions 中进行处理,这样 devtools 就能够进行跟踪,由 Actions 处理异步操作,具体的函数部分仍交由 Mutations 进行处理。
actions:{
setCart(context,data){
setTimeout(()=>{
context.commit("SET_CARTNUM",data)
},4000)
}
}
5.modules
分模块管理数据
const moduleA = {
state:{
name: 'moduleA'
},
mutations:{
updateName(state,payload){
state.name = payload
}
},
getters:{
fullname(state){
return state.name + '1111'
},
fullname2(state, getters){
return getters.fullname + '2222'
},
fullname3(state, getters, rootState){
//传入第三个参数:rootState为上一个store对象中的state
return getters.fullname2 +rootState.counter
}
},
actions:{
aUpdateName(context){//context 中 的commit只指向该模块中的mutations
setTimeout(() => {
context.commit('updateName','xiaowang')
console.log(context)
},
const store = new Vuex.Store({
state:{
counter:1000,
students:[
{id:110, name: 'name1', age: 12},
{id:111, name: 'name2', age: 21},
{id:112, name: 'name3', age: 22},
{id:113, name: 'name4', age: 20},
{id:114, name: 'name5', age: 18}
],
info:{
name: 'kobe',
age: 40,
height: 1.89
}
},
mutations:{//定义一些方法
increment(state){
state.counter++
},
decrement(state){
state.counter--
},
incrementCount(state, payload){
//1.普通提交方式
//state.counter += count
//2.特殊提交方式
state.counter += payload.count
},
addStudent(state, obj){
state.students.push(obj)
},
updateInfo(state){
state.info.name = 'Jams'
}
},
getters:{
powerCounter(state){
return state.counter * state.counter
},
more20stu(state){
return state.students.filter(s => s.age > 20)
},
more20stuLength(state,getters){
return getters.more20stu.length
},
moreAgeStu(state){
return function(age){
return state.students.filter(s => s.age > age)
}
}
},
actions:{
//context:上下文 === store
aUpdateInfo(context, payload){
return new Promise((resolve, reject)=>{
setTimeout(() => {
context.commit('updateInfo');
console.log(payload);
resolve('11111')
}, 1000);
})
}
},
modules:{
a: moduleA
}
})
四、vuex的映射
1.mapState
把vuex的state 在computed映射为组件的data
...mapState({
score:state=>state.test.score
})
2.mapGetters
(1)没有命名空间
...mapGetters({
fee:"fee"
}),
...mapGetters(["fee"]),
(2)有命名空间
...mapGetters({
"rank":"test/rank"
})
3.mapMutations
(1)没有命名空间
...mapMutations({
"setUser":"SET_USERINFO"
})
(2)有命名空间
...mapMutaions:{
"setScore":"test/SET_SCORE"
}
4.mapActions
(1)没有命名空间
...mapActions({
login:"login"
}),
...mapActions(["login"])
}
(2)有命名空间
...mapActions({
log:"test/login"
})