store.js
// vuex的核心管理模块
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//状态对象
const state={//初始化状态
count: 0
}
//包含多个更新state函数的对象
const mutations={
//增加的mutation
INCREMENT() {
state.count++
},
//减少的mutation
DECREMENT() {
state.count--
}
}
//包含多个对应事件回调函数的对象
const actions={
//增加的action
increment({commit}) {
//提交增加的mutation
commit('INCREMENT')
},
//减少的action
decrement({commit}) {
commit('DECREMENT')
},
//带条件的action
incrementIfOdd({commit,state}){
if(state.count%2===1){
commit('INCREMENT')
}
},
//异步的action
incrementAsync({commit}){
setTimeout(()=>{
commit('INCREMENT')
},1000)
},
}
//包含多个getter计算属性函数的对象
const getters={
evenOrOdd(state) {
return state.count % 2 === 0 ? '偶数' : '奇数';
}
}
export default new Vuex.Store({
state,//状态对象
mutations,//包含多个更新state函数的对象
actions,//包含多个对应事件回调函数的对象
getters,//包含多个getter计算属性函数的对象
})
VueTest.vue
<template>
<div>
<!-- <p>click {{$store.state.count}} times, count is {{evenOrOdd}}</p>-->
<p>click {{count}} times, count is {{evenOrOdd}}</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>
</div>
</template>
<script>
import { mapActions, mapState, mapGetters } from 'vuex';
export default {
name: 'VuexTest',
computed: {
...mapState(['count']),//mapState()返回值:{count(){return this.$store.state['count']}}
...mapGetters(['evenOrOdd'])//mapGetters()返回值:{evenOrOdd(){return this.$store.getters['evenOrOdd']}}
// evenOrOdd() {
// //return this.count % 2 === 0 ? '偶数' : '奇数';
// // return this.$store.getters.evenOrOdd
// }
},
methods:{
...mapActions(['increment','decrement','incrementIfOdd','incrementAsync'])
}
// methods: {
// //增加
// increment() {
// // const count = this.count;
// // this.count = count + 1;
// this.$store.dispatch('increment');//触发store中对应action
// },
// //减少
// decrement() {
// // const count = this.count;
// // this.count = count - 1;
// this.$store.dispatch('decrement');//触发store中对应action
// },
// //奇数增加
// incrementIfOdd() {
// this.$store.dispatch('incrementIfOdd');//触发store中对应action
// // const count = this.count;
// // if(count%2===1){
// // this.count=count+1
// // }
// },
// //过一秒增加
// incrementAsync() {
// this.$store.dispatch('incrementAsync');//触发store中对应action
// // setTimeout(()=>{
// // const count = this.count;
// // this.count = count + 1;
// // },1000)
// }
// }
};
</script>
<style scoped>
</style>