- 使用vuex也有一段时间了,今天总结一下vuex的使用
- vuex有5个核心概念
state ``````getter``````mutation``````action``````module
state
this.$store.state.xxx
或者使用mapState
getter
this.$store.getters.xxx
或者使用mapGetter
mutation
this.$store.commit(“xxx”)
或者使用mapMutations
action
this.$store.dispatch(“xxx”)
或者使用mapActions
module
Vuex 允许我们将store分割成模块(module)。
每个模块拥有自己的 state、mutation、action、getter
建议在使用module时,启动命名空间
案例
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
getters: {
doubleCount(state) {
return state.count * 2
}
},
mutations: {
increment(state,n) {
state.count += n
},
decrement(state) {
state.count--
}
},
actions: {
INCREMENT({commit},n) {
commit('increment',n)
},
DECREMENT({commit}) {
commit('decrement')
},
ASYN_INCREMENT({commit},n) {
setTimeout(() => {
commit('increment',n)
},2000)
},
}
})
app.vue
<template>
<div id="app">
{{ count }}
<br />
{{ doubleCount }}<br />
<button @click="INCREMENT(2)">count++</button>
<button @click="DECREMENT">count--</button>
<button @click="ASYN_INCREMENT(3)">异步count++</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from "vuex";
export default {
computed: {
...mapState([
'count'
]),
...mapGetters([
'doubleCount'
])
},
methods: {
...mapActions([
'INCREMENT',
'DECREMENT',
'ASYN_INCREMENT'
])
}
};
</script>
<style scoped>
#app {
text-align: center;
}
</style>