组件交互模式的使用场景
- 简单应用直接使用props down,event up的模式就可以了
- 小型应用使用事件中心模式即可
- 中大型应用使用vuex的状态管理模式
vuex
包含要管理的应用数据和更新数据的methods,其他组件使用 store.commit('increment')
即可完成数据操作.
// Make sure to call Vue.use(Vuex) first if using a module systemconst 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
{
{ count }}
// make sure to call Vue.use(Vuex) if using a module systemconst 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') } }})