import Vue from 'vue' import Vuex from 'vuex' //注册vuex插件 Vue.use(Vuex)
// root state object. // each Vuex instance is just a single state tree. //定义state const state = { count: 0 }
// mutations are operations that actually mutates the state. // each mutation handler gets the entire state tree as the // first argument, followed by additional payload arguments. // mutations must be synchronous and can be recorded by plugins // for debugging purposes. //定义mutations const mutations = { increment (state) { state.count++ }, decrement (state) { state.count-- } }
// actions are functions that cause side effects and can involve // asynchronous operations. //定义actions const actions = { increment: ({ commit }) => commit('increment'), decrement: ({ commit }) => commit('decrement'), incrementIfOdd ({ commit, state }) { if ((state.count + 1) % 2 === 0) { commit('increment') } }, incrementAsync ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('increment') resolve() }, 1000) }) } }
// A Vuex instance is created by combining the state, mutations, actions, // and getters. //导出vuex实例 export default new Vuex.Store({ state, getters, actions, mutations }) ```
首先注册vuex插件
```vuejs import Vue from 'vue' import Vuex from 'vuex'
Vue.use(Vuex)
然后分别定义state、mutations、actions、getters,并导出
最后将vuex对象实例挂载到vue的每一个实例上去
1 2 3 4 5 6
new Vue({ el: '#root', router, store, render: h => h(App) })