06笔记vuex actions 04

// App.vue
<template>
  <div id="app">    
    {{ count }}
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </div>
</template>

<script>
import { mapState } from 'vuex';
// import { mapState, mapActions } from 'vuex';
export default {
  name: 'app',
  computed: mapState([
    'count'
  ]),
  methods: {
    increment () {
      // this.$store.commit('increment');
      this.$store.dispatch('incrementAsync');
    },
    decrement () {
      // this.$store.commit('decrement');
      this.$store.dispatch('decrement');
    },
    testAction () {
      this.$store.dispatch('actionA').then(() => {
        
      });
    }
  }
  // methods: mapActions([
  //   'increment',
  //   'decrement'
  // ])
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

// 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++;
    },
    decrement (state) {
      state.count--;
    }
  },
  actions: {
    // increment (context) {
    //   context.commit('increment');
    // }
    increment ({ commit }) {
      commit('increment');
    },
    decrement ({ commit }) {
      commit('decrement');
    },
    incrementAsync ({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    },
    actionA ({ commit }) {
      return new Promise((resolve) => {
        setTimeout(() => {
          commit('someMutation');
          resolve();
        }, 1000);
      });
    },
    actionB ({ dispatch, commit }) {
      return dispatch('actionA').then(() => {
        commit('someOtherMutation');
      })
    },
    actionC ({ commit }) {
      commit('gotData', await getData());
    },
    actionD ({ dispatch, commit }) {
      await dispatch('actionC');
      commit('gotOtherData', await getOhterData());
    }
  }
});


new Vue({
  render: h => h(App),
  store
}).$mount('#app')

发布了135 篇原创文章 · 获赞 67 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_25479327/article/details/104207596