解决的问题:
解决数据之间需要存在保持一致性的问题
组件访问State中的数据的方式:
1.通过this.$Sorte.state.全局数据名称
1.导入import {mapState} from 'vuex'
2.在需要导入的vue组件中加入计算属性:
computed:{
...mapState{['count']}
}
Mutation用于变更Store中的数据
mutation不能处理异步操作
1.只能通过mutation变更数据,不可以直接操作Store中的数据。
2.通过这种方式虽然操作起来稍微繁琐一点,但是可以集中监控所有数据的变化
定义Mutation
const store =new Vuex.store({
state:{
count:0
},
mutation:{
add(state){
//变更状态
state.count++
}
}
})
触发mutation
methods:{
handle1(){
this.$store.commit('add')
}
}
定义Mutation
const store =new Vuex.store({
state:{
count:0
},
mutation:{
add(state,step){
//变更状态
state.count+=step
}
}
})
commit的作用就是调用某个mutation
触发mutation
methods:{
handle2(){
this.$store.commit('add',3)
}
}
触发mutation的第二种方式
1.从vue中按需导入mapMutations函数
import [mapMutations] from 'vuex'
2.将指定的mutations函数,映射为当前组件的methods方法
methods:{
...mapMutations(['add','addN'])
}
commit的作用是触发mutation
dispatch的作用是触发action
触发actions异步任务时携带参数:
//定义Action
const store=new vuex.store({
matation:{
addN(state,step){
state.count+=step
}
},
action:{
addNsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
)}
触发Action
methods:{
handle(){
this.$store.dispath('addNAsynv',3)
}
}
触发Action的第二种方式
1.从vue中按需导入mapActions函数
import [mapActions] from 'vuex'
2.将指定的mutations函数,映射为当前组件的methods方法
methods:{
...mapActions(['add','addN'])
}
1.Getter 用于对Store中的数据进行加工处理后形成新数据
2.store中数据发生变化,Getter的数据也会跟着变化
const store = new vuex.store({
state:{
count:0
},
getters:{
showNun:state=>{
return'当前最新的数量是['+state.count+']'
}
}
})
使用getters的第一种方式
this.$store.getters.名称
使用gerrers的第二种方法:
import { mapGetters } from 'vuex'
computed:{
...mapGetters({'showNum'})
}