// App.vue
<template>
<div id="app">
{{ count }}<br/>
<button @click="increment">+1</button><br/>
<button @click="incrementBy">+5</button><br/>
<hr/>
<button @click="decrement">-1</button><br/>
<button @click="decrementBy">-5</button><br/>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: 'App',
computed: mapState([
'count'
]),
methods: {
increment () {
this.$store.commit('increment');
},
incrementBy () {
this.$store.commit('incrementBy', 5);
},
decrement () {
this.$store.commit('decrement', { amount: 1});
},
decrementBy () {
this.$store.commit({
type: 'decrementBy',
amount: 5
});
}
}
}
</script>
// main.js
import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'
Vue.use(Vuex);
Vue.config.productionTip = false
const store = new Vuex.Store({
state: {
count: 5
},
mutations: {
increment (state) {
state.count++;
},
incrementBy (state, n) {
state.count += n;
},
decrement (state, payload) {
state.count -= payload.amount;
},
decrementBy (state, payload) {
state.count -= payload.amount;
}
}
})
console.log(store.state.count);
new Vue({
store,
render: h => h(App),
}).$mount('#app')
// main.js
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
Vue.use(Vuex)
Vue.config.productionTip = false
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
},
incrementBy (state, n) {
state.count += n;
},
incrementBy2 (state, playload) {
state.count += playload.amount;
}
}
});
store.commit('increment');
// store.commit('incrementBy', 9);
store.commit('incrementBy2', {
amount: 19
});
window.console.log(store.state.count);
new Vue({
render: h => h(App),
store
}).$mount('#app')
对象风格提交方式
// main.js
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
Vue.use(Vuex)
Vue.config.productionTip = false
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
},
incrementBy (state, n) {
state.count += n;
},
incrementBy2 (state, playload) {
state.count += playload.amount;
}
}
});
store.commit('increment');
// store.commit('incrementBy', 9);
// store.commit('incrementBy2', {
// amount: 19
// });
store.commit({
'type': 'incrementBy2',
amount: 9
})
window.console.log(store.state.count);
new Vue({
render: h => h(App),
store
}).$mount('#app')