vuejs组件交互 - 03 - vuex状态管理实现组件交互

组件交互模式的使用场景

  1. 简单应用直接使用props down,event up的模式就可以了
  2. 小型应用使用事件中心模式即可
  3. 中大型应用使用vuex的状态管理模式

vuex

包含要管理的应用数据和更新数据的methods,其他组件使用 store.commit('increment')即可完成数据操作.

// Make sure to call Vue.use(Vuex) first if using a module system

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

store.commit('increment')

console.log(store.state.count) // -> 1

live demo

<div id="app">
  <p>{{ count }}</p>
  <p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </p>
</div>
// make sure to call Vue.use(Vuex) if using a module system

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
  	increment: state => state.count++,
    decrement: state => state.count--
  }
})

new Vue({
  el: '#app',
  computed: {
    count () {
	    return store.state.count
    }
  },
  methods: {
    increment () {
      store.commit('increment')
    },
    decrement () {
    	store.commit('decrement')
    }
  }
})
posted @ 2017-08-09 23:02  CooMark  阅读(395)  评论(0编辑  收藏  举报