传递可观察数据/参数的最佳做法是什么,以便当它被子组件修改时,我可以访问新值?
道具的流动是一种方式,孩子不应该直接修改它的道具。
对于复杂的应用程序,vuex 是解决方案,但对于简单的情况,vuex 是大材小用。就像@Belmin 所说的那样,由于反应系统,您甚至可以使用纯 JavaScript 对象。
另一种解决方案是使用事件。Vue 已经实现了 EventEmitter 接口,一个孩子可以使用this.$emit('eventName', data)
它来与它的父母沟通。
父母将像这样监听事件:(@update
是的简写v-on:update
)
<child :value="value" @update="onChildUpdate" />
并更新事件处理程序中的数据:
methods: {
onChildUpdate (newValue) {
this.value = newValue
}
}
这是 Vue 中自定义事件的简单示例:
http ://codepen.io/CodinCat/pen/ZBELjm?editors=1010
这只是父子通信,如果一个组件需要与其兄弟通信,那么你将需要一个全局事件总线,在 Vue.js 中,你可以只使用一个空的 Vue 实例:
const bus = new Vue()
// In component A
bus.$on('somethingUpdated', data => { ... })
// In component B
bus.$emit('somethingUpdated', newData)