store/index.js
import Vue from 'vue'
import Vuex from 'vuex';
// 使用vuex
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
myCount(state) {
return `current count is ${state.count}`
}
},
mutations: {
increment(state) {
state.count += 1;
},
decrement(state) {
state.count -= 1;
}
},
actions: {
myIncrease(context) {
context.commit('increment')
},
myDecrease(context) {
context.commit('decrement')
}
}
})
export default store;
Demo vuex
<template>
<div class="container">
<h1>{{ count }}</h1>
<h1>{{ myCount }}</h1>
<div>
<button type="button" @click="increase">增加</button>
<button type="button" @click="decrease">减少</button>
</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
export default {
name: "vuex",
computed: {
...mapState(["count"]),
...mapGetters(["myCount"])
},
methods: {
...mapMutations(["increment", "decrement"]),
...mapActions(["myIncrease", "myDecrease"]),
increase() {
// this.$store.commit('increment')
// this.increment();
// this.$store.state.count += 1;
this.myIncrease()
},
decrease() {
// this.$store.commit('decrement')
// this.decrement();
// this.$store.state.count -= 1;
this.myDecrease()
}
}
};
</script>
<style>
</style>