目标
1.熟练使用mapState
2.熟练使用mapGetters
3.熟练使用mapActions
4.熟练使用mapMutations
知识点
首先在讲解用法前我们先创建一个仓库实例
import Vue from 'vue'
import Vuex from 'vuex'
import { Mockurl} from '@/until'
Vue. use ( Vuex)
export default new Vuex. Store ( {
state: {
count: 0 ,
data: [ ] ,
sex: 0
} ,
mutations: {
changeData ( state, actions) {
state. data = [ ... actions. data]
} ,
add ( state) {
++ state. count
} ,
dis ( state) {
-- state. count
}
} ,
actions: {
getData ( store, payload) {
axios. get ( '/get/data' ) . then ( data=> {
store. commit ( 'changeData' , data)
} )
}
} ,
getters: {
sex ( state) {
return state. sex === 0 ? '男' : '女'
}
}
} )
mapState读取仓库状态
< template>
< div> { { count} } < / div>
< / template>
< script>
import { mapState } from 'vuex'
export default {
computed: {
... mapState ( [ 'count' ] ) ,
}
}
< / script>
mapMutations 修改仓库状态
< template>
< div>
< span @click= "dis" > - < / span>
{ { count} }
< span @click= "add" > + < / span>
< / div>
< / template>
< script>
import { mapMutations } from 'vuex'
export default {
methods: {
... mapMutations ( [ 'add' , 'dis' ] )
}
}
< / script>
mapActions 异步处理
< script>
import { mapActions } from 'vuex'
export default {
methods: {
... mapActions ( [ 'getData' ] )
}
}
< / script>
getters 数据派生
< template>
< div>
性别: { { sex} }
< / div>
< / template>
< script>
import { mapGetters } from 'vuex'
export default {
computed: {
... mapGetters ( [ 'sex' ] )
}
}
< / script>