第一步:安装vuex
第二步:store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //存储 $store.state.count
count:0
},
mutations: { //修改值 this.$store.commit('addCount',n)
addCount (state ,n = 0) {
return (state.count += n)
}
},
actions: {
actionsAdd(context,n = 0) { // 异步操作 this.$store.dispatch('actionsAdd',n)
console.log(context);
return context.commit('addCount',n)
}
},
getters: {
getterCount:(state) => {// 计算,例如根据值来判断输出啥 return this.$store.getters.getterCount
return state.count%2 ? '奇数' : '偶数'
}
}
})
main中
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')