06筆記vuex actions 02

// App.vue
<template>
  <div id="app">
    {{ count }}<br/>
    <button @click="increment">+1</button><br/>
    <button @click="incrementAsync">+1 (async)</button><br/>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name: 'App',
  computed: mapState([
    'count'
  ]),
  methods: {
    increment () {
      // this.$store.commit('increment');
      this.$store.dispatch('increment');
    },
    incrementAsync () {
      // this.$store.commit('decrement');
      this.$store.dispatch('incrementAsync');
    }
  }
}
</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: 0
  },
  mutations: {
    increment (state) {
      state.count++;
    },
    decrement (state) {
      state.count--;
    }
  },
  actions: {
    // increment (context) {
    //   context.commit('increment');
    // }
    increment ({ commit }) {
      commit('increment');
    },
    incrementAsync ({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  }
});


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章