vuex的核心概念
State
-
state提供唯一的公共数据源,所有共享数据都要统一放到Store的State中进行存储
-
组件访问State中数据的第一种方式:this.$state.全局数据名称
-
第二种方式
-
1.从vuex中按需导入mapState函数//
-
import {mapState} from 'vuex'
-
通过刚才导入的mapState函数,将当前组件需要的全局数据映射为当前组件的computed计算属性
-
2.将全局组件映射为当前组件的计算属性
computed:{ ...mapState(['count']) }
-
mutation
mutation 用于变更Store中的数据
- 只能通过mutation变更Store数据,不可以直接操作Store中的数据
- 只能通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
//定义
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
//变更状态
state.count++
}
}
})
//触发mutation
methods:{
handle1(){
//第一种方式
this.$store.commit('add')
}
}
可以在触发mutations时传递参数:commit
//定义mutation
const store =new Vuex.Store({
state:{
count:0
},
mutations:{
addN(state,step){
//change state
state.count+=step
}
}
})
//trigger mutation
methods:{
handle2(){
//在调用commit函数
//触发mutations时携带参数
this.$store.commit('addN',3)
}
}
this.$store.commit()是触发mutations的第一种方式,触发mutations的第二种方式:
//1.从vuex中按需导入mapMutations函数
import{mapMutation} from 'vuex'
通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:
methods:{
...mapMutations(['add','addN'])
}
mutations不可以写异步函数
action
action用于处理异步任务 action无法修改state数据
如果通过异步操作变更数据,必须通过Action,而不能Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
//定义Acton
const store = new Vuex.store({
mutations:{
add(state){
state.count++
}
},
actions:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
})
//触发Action
methods:{
handle(){
//触发actions的第一种方式
this.$store.dispatch('addAsync')
}
}
触发actions异步任务时携带参数
//定义Acton
const store = new Vuex.store({
mutations:{
addN(state){
state.count++
}
},
actions:{
addNAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
})
//触发Action
methods:{
handle(){
//触发actions的第二种方式
this.$store.dispatch('addAsync',5)
}
}
this.$store.dispatch()是触发actions的第一种方式,触发actions的第二种方式
//1.从vuex中按需导入mapActions函数
import {mapActons} from 'vuex'
通过导入刚才的mapActions函数将需要的actions函数,映射为当前组件的methods方法:
//2.将指定的actions函数,映射为当前组件的methods函数
methods:{
...mapActions(['addAsync','addNAsync'])
}
Getter
Getter用于对Store中的数据进行加工处理形成新的数据
- getter可以对Store中已有的数据加工处理之后形成新的数据,类似于Vue的计算属性。
- Store中数据发生变化,getter的数据也会跟着变化。
//定义Getter
const store = new Vuex.Sore({
state:{
count:0
},
getters:{
showNum:state=>{
return '当前最新的数量是【'+state.coun+'】'
}
}
})
使用getter的第一种方式:
this.$store.getters.name
第二种方式
import {mapGetters} from 'vuex'
computed:{
...mapGetters(['showNum'])
}