一、vuex定义count

  1. export default new Vuex.Store({
  2. state: {
  3. count:1
  4. }
  5. })

二、在组件中派发一个事件给vuex的actions

this.$store.dispatch()

  1. <template>
  2. <div class="home">
  3. <button @click="add">
  4. {{this.$store.state.count}}</button>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: 'Home',
  10. methods:{
  11. add(){
  12. this.$store.dispatch("add")
  13. }
  14. }
  15. }
  16. </script>

三、在vuex的actions中接收组件派发过来的事件

  1. export default new Vuex.Store({
  2. actions: {
  3. add(ctx){
  4. console.log(ctx);
  5. ctx.commit("addCount")
  6. }
  7. }
  8. })

四、在actions中通过commit提交一个事件给mutations,在mutations中改变state

  1. export default new Vuex.Store({
  2. state: {
  3. count:1
  4. },
  5. mutations: {
  6. addCount(state){
  7. console.log("state");
  8. state.count++;
  9. }
  10. }
  11. })