您的位置:首页 > 产品设计 > UI/UE

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

2017-08-09 23:02 821 查看

组件交互模式的使用场景

简单应用直接使用props down,event up的模式就可以了

小型应用使用事件中心模式即可

中大型应用使用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')
}
}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: