vuex:集中式管理数据http://vuex.vuejs.org/安装项目:cnpm install安装vuex: cnpm install vuex -Dvuex提供个两个方法: mapActions:管理所有事件 mapGetters:获取数据
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}}
store.js
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);var state = { count: 10 //不能有分号};const mutations = { //处理const actions后的操作 increment(state) { //处理状态(数据)变化 state.count++; }, decrement(state) { state.count--; }};const actions = { //接受页面的点击事件 increment: ({ //处理你要干什么,异步请求,判断,流程控制 commit }) => { commit('increment') //commit是函数,提交给mutations的increment(state) }, decrement: ({ commit }) => { //不用箭头函数也可以 commit('decrement'); }, clickOdd: ({ commit, state }) => { if (state.count % 2 == 0) { commit('increment')//提交动作 } }, clickAsync: ({ commit }) => { new Promise((resolve) => { //Promise是es6的 setTimeout(function() { commit('increment'); resolve();//继续向下走 }, 1000); }); }};const getters = { //页面获取{ {count}},{ {getOdd}} count(state) { return state.count; }, getOdd(state) { return state.count % 2 == 0 ? '偶数' : '奇数'; }};//需要导出Store对象export default new Vuex.Store({ state, mutations, actions, getters});