1 安装:npm i vuex
2 引入vuex: import Vuex from 'Vuex'
vue上使用vuex: vue.use(vuex)
3、创建vuex对象:const store = new Vuex.Store()
暴露vue:export default store
3、将store对象挂载到vue实例中: new vue({ el: render: store: })
4、state提供唯一的公共源数据。state存放的是对象
组将访问state数据第一种方式:
this.$store.state.全局数据的名称
5 组件访问state中第二方式:
1、导入mapstate函数 : import {mapSatate} from vuex
2、导入的mapState函数,将当前组件需要的全局数据,映射为当前的组价。展开运算符,把全局属性进行映射。 compited:{...mapState(['count'])}
6、mutation变更store的数据,不能直接修改store的数据。 但是可以监控所有数据的变换。 我想+1是不行的。
mutations:{add(state){state.count++}//变更状态 } state就是当前的全局函数。
mutations:{add(state,step){state.count+=step}}
什么时候调用呢。 怎么调用呢。
this.$store.commit('add')
this.$store.commit('addN,3) //传参。
7、Action用于异步处理:
如果通过异步操作,必须通过Action,不能用muation。但是在action里面用mutation方式间接变更。
定义函数:
mutations:{add(state){state.count++}}
action:{addAsync(context){setTimeout(()=>{context.commit('add')}),100}}
通过context调用muatations的方法,不能直接修改数据!。
触发action:action this.$store.dispatch('addAsync')
触发携带参数:
muations:{}
1 dispatch触发的时候传参数。2 actions形参变量:step。3 commint的()addN,step )
4 mutation的形参addN(state,step)5state.count+=step
action:addNAsync(context, step ){ setTimeout(()=>{context.comit('addN', setp ),1000})}
mution:{add(state,step){count+=step}
触发this.$store.dispatch('addASYC',c)
8第二种方式 1 import {mapActions} 2 ..mapActions
9getter类似于vue计算属性。 getter:{showNum:state=》{return }}包装数据
使用this.$store.getter.名称。
mapGetters computed:{...mapGetters['showNum']}