Count.vue
<template>
<div class="count">
<h2>当前求和为:{{ $store.state.sum }}</h2>
<!-- v-model.number收到的数值转换为number -->
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name: "TheCount",
data() {
return {
n: 1,
};
},
methods: {
increment() {
this.$store.commit("add", this.n);
},
decrement() {
this.$store.commit("minus", this.n);
},
incrementOdd() {
this.$store.dispatch("addObb", this.n);
},
incrementWait() {
this.$store.dispatch("addWait", this.n);
},
},
mounted() {},
};
</script>
<style>
.count {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
width: 300px;
height: 400px;
}
button,
select,
h2 {
width: 300px;
height: 30px;
}
</style>
index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const actions = {
addObb(context, value) {
if (context.state.sum % 2) context.commit('addObb', value);
},
addWait(context, value) {
setTimeout(() => {
context.commit('ADD', value);
}, 1000)
}
};
const mutations = {
ADD(state, value) {
state.sum += value;
},
minus(state, value) {
state.sum -= value;
},
addObb(state, value) {
state.sum += value;
},
addWait(state, value) {
state.sum += value;
}
};
const state = {
sum: 0
};
export default new Vuex.Store({
actions,
mutations,
state
});
App.vue
<template>
<div id="app" class="align">
<count />
</div>
</template>
<script>
import Count from "./components/Count.vue";
export default {
name: "App",
components: { Count },
};
</script>
<style scoped>
</style>
main.js
import Vue from 'vue';
import App from './App.vue'
import store from './store/index';
new Vue({
render: h => h(App),
store,
}).$mount('#app');