一、vuex的基本使用
1,安装vuex
npm install vuex --save
2,导入vuex,并引用一下
import Vuex from 'vuex'
Vue.use(Vuex)
3,创建实例对象,
const store = Vuex.store({
state:{},
mutations:{},
actions:{},
getters:{},
modules:{}
})
4,导出store对象,挂载到Vue实例中
二、核心概念
state ->单一状态树
mutations ->vuex的store状态的更新唯一方式
incrementCount(state,payload){//state参数即state里面的数据,payload即组件传过来的参数集合
state.counter += payload.count
},
actions ->异步的一些操作
aUpdateInfo(context,payload){//context参数想到那个鱼store
return new Promise((resolve,reject) => {
setTimeout(() => {
context.commit('upDateName')
console.log(payload);
})
})
}
getters ->有点像computed
excellentStudentLength(state,getters){//state参数即state里面的数据,getters参数即getters里面的方法
return getters.excellentStudent.length
},
modules ->模块
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 的状态 模块内的state和store里的store是相同的
store.state.b // -> moduleB 的状态 模块内的state和store里的store是相同的
三、vuex的组成结构
1,组件直接提交到mutations
addCount(count){
方式一:
this.$store.commit('incrementCount',count)
方式二:
this.$store.commit({
type:'incrementCount',
count
})
}
2,组件先到达actions,再由actions到mutations
组件中:
asyncUpdateName(){
this.$store
.dispatch('aUpdateInfo','我是携带的信息')
.then(res => {
console.log('里面完成了提交');
console.log(res);
})
}
actions中:
aUpdateInfo(context,payload){
return new Promise((resolve,reject) => {
setTimeout(() => {
context.commit('upDateName')
console.log(payload);
resolve(1111111111)
})
})
}