1.npm install vuex --save
2.在main.js中引用(或者单独写一个js文件,然后在引用到main.js中也可以)
import vuex from 'vuex'
Vue.use(vuex)
const store=new Vuex.Store({
state:{
count:0
},
mutations:{
increment(state){
state.count++;
}
}
})
在vue实例中添加store属性,这样可以映射到没一个子组件中,子组件可以通过this.$store来获取store对象
3.state
- 用来存一些公共状态的变量,但是不能直接修改state里面的变量,而是通过commit mutation的方式来修改state里的变量,这样可以更加明确的追踪状态变化
- mapState辅助函数,当在一个子组件中需要获取多个状态变量时,一一获取会比较麻烦,这时可以使用mapState函数
computed:{
count(){
....
},
...mapState([
'increment' //这个会将state变量里面的increment属性映射为计算属性increment(){this.$store.state.increment}
])
}
4.getters,类似于vue的计算属性,它的返回值会根据其依赖的属性缓存,只有依赖的属性发生改变时,才会重新计算
- getters:{
}
- mapGetters辅助函数
import {mapState} from 'vuex'
computed:{
...mapGetters(['count'])
}
computed:{
mapGetters({
seconCount:'count' //将getters里面的count属性映射为seconCount计算属性
})
}
- 通过属性访问this.$store.getters.count结果是响应式的,如果通过方法访问则不是
5.mutations,通过提交mutation来改变state里的属性,是同步操作
- 基本写法
mutations:{
increment(state){
state.count++;
}
}
子组件中this.$store.commit('increment')
- 提交载荷
mutations:{
increment(state,payload){
state.count++;
}
}
子组件中this.$store.commit('increment',payload)//patload可以是一个变量或者对象
已对象形式提交this.$store.commit({
type:'increment',
payload:{}
})
- mapMutations 映射到methods里面,用法同mapState,mapMutations一样
6.actions 类似于mutations ,是属于异步操作,提交的是mutation
- 基本写法
actions:{
increment(context){context.commit('mutaionName')}//context对象具有和store一样的属性和方法(也可以获取state和getters)
increment({commit}){commit('mutaionName')}//参数结构写法
}
- mapActions用法和mapMutations一致
- 分发action this.$store.dispach('increment')
- action和promise函数组合
7.module
modules: { a: moduleA, b: moduleB } store.state.a来使用各自的属性
computed:{
...mapState({
count:state=>{state.a.count} //不能简写否则映射不到
})
}