src main.js App.vue store actions.js actions.js index.js mutations.js types.js
main.js
import Vue from 'vue'import App from './App.vue'import store from './store/'new Vue({ store, el: '#app', render: h => h(App)})
App.vue
welcome vuex-demo
现在数字为: { {count}}, 它现在是 { {getOdd}}
action.js
import * as types from './types'export default { increment: ({ commit }) => { commit(types.INCREMENT); }, decrement: ({ commit }) => { commit(types.DECREMENT); }, clickOdd: ({ commit, state }) => { if (state.mutations.count % 2 == 0) { commit(types.INCREMENT); } }, clickAsync: ({ commit }) => { new Promise((resolve) => { setTimeout(function() { commit(types.INCREMENT); }, 1000); }) }}
getters.js
export default { count: (state) => { return state.count; }, getOdd: (state) => { return state.count % 2 == 0 ? '偶数' : '奇数' }}
index.js
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);import mutations from './mutations'import actions from './actions'export default new Vuex.Store({ modules:{ mutations }, actions});
mutation.js
import { INCREMENT, DECREMENT} from './types'import getters from './getters'const state = { count: 20};const mutations = { [INCREMENT](state) { state.count++; }, [DECREMENT](state) { state.count--; }};export default { state, mutations, getters}
types.js
export const INCREMENT = 'INCREMENT';export const DECREMENT = 'DECREMENT';