vuex实现了统一状态管理,这里记录基础配置及使用方法
//store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 1,
isShow: true
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
},
toggleState (state) {
state.isShow = !state.isShow
}
},
actions: {
increment (context) {
context.commit('increment')
},
decrement (context) {
context.commit('decrement')
},
incrementIfOdd ({commit, state}) {
if (state.count % 2 == 1) commit('increment')
},
incrementAsync ({commit}) {
setTimeout(() => {
commit('increment')
}, 1000)
},
toggleState ({commit}) {
commit('toggleState')
}
},
getters: {
evenOrOdd (state) {
return state.count % 2 == 0? '偶数': '奇数'
}
},
modules: {}
})
<template>
<div id="">
<!-- MyStoreDemo组件 -->
<div class="vuex">
<h1>Vuex 示例</h1>
<el-button :type="isShow==false?'primary':'danger'" v-text="isShow==false?'显示':'隐藏'"
@click="toggleState"></el-button>
<template v-if="isShow">
<p class="p-vuex">click {{count}} times, count is {{evenOrOdd2}}</p>
<el-button type="primary" @click="increment">增加</el-button>
<el-button type="primary" @click="decrement">减少</el-button>
<el-button type="primary" @click="incrementIfOdd">奇数增加</el-button>
<el-button type="primary" @click="incrementAsync">异步增加</el-button>
</template>
</div>
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {
name: 'MyStoreDemo',
data() {
return {}
},
computed: {
...mapState(['count', 'isShow']),
...mapGetters({'evenOrOdd2': 'evenOrOdd'}),
// count () {
// return this.$store.state.count
// },
// evenOrOdd2 () {
// return this.$store.getters.evenOrOdd
// }
},
methods: {
...mapMutations(['increment', 'decrement']),
...mapActions(['incrementIfOdd', 'incrementAsync', 'toggleState']),
// increment () {
// this.$store.dispatch('increment')
// },
// decrement () {
// this.$store.dispatch('decrement')
// },
// incrementIfOdd () {
// this.$store.dispatch('incrementIfOdd')
// },
// incrementAsync () {
// this.$store.dispatch('incrementAsync')
// },
// toggleState () {
// this.$store.dispatch('toggleState')
// }
}
}
</script>
<style scoped>
.p-vuex {
line-height: 30px;
font-size: 20px;
}
</style>