Vue 组件通信 [英] Vue components communication
问题描述
我有两个 Vue 组件:
I have two Vue components:
Vue.component('A', {});
Vue.component('B', {});
如何从组件 B 访问组件 A?组件之间的通信是如何工作的?
How can I access component A from component B? How does the communication work between the components?
推荐答案
跨组件通信在 Vue.js 文档中没有得到太多关注,也没有很多教程涉及这个主题.由于组件应该被隔离,因此您永远不应该直接访问"组件.这会将组件紧密耦合在一起,而这正是您想要防止的.
Cross-component communication doesn't get much attention in the Vue.js docs, nor are there many tutorials that cover this subject. As components should be isolated, you should never "access" a component directly. This would tightly couple the components together, and thats exactly what you want to prevent doing.
Javascript 有一种极好的通信方式:事件.Vue.js 内置了事件系统,主要用于父子通信.来自文档:
Javascript has an excellent method for communication: events. Vue.js has a built-in event system, mainly used for parent-child communication. From the docs:
虽然可以直接访问 Vue 实例的子级和父级,但是使用内置的事件系统进行跨组件通信更方便.它还使您的代码更少耦合且更易于维护.一旦建立了父子关系,您就可以使用每个组件的事件实例方法来调度和触发事件.
Although you can directly access a Vue instance’s children and parent, it is more convenient to use the built-in event system for cross-component communication. It also makes your code less coupled and easier to maintain. Once a parent-child relationship is established, you can dispatch and trigger events using each component’s event instance methods.
他们用来说明事件系统的示例代码:
Their example code to illustrate the event system:
var parent = new Vue({
template: '<div><child></child></div>',
created: function () {
this.$on('child-created', function (child) {
console.log('new child created: ')
console.log(child)
})
},
components: {
child: {
created: function () {
this.$dispatch('child-created', this)
}
}
}
}).$mount()
Dan Holloran 最近在 两个 件.如果您需要在没有父子关系的组件之间进行通信,这可能对您有所帮助.
Dan Holloran has recently written a piece on his "struggle" with cross-component messaging, in two pieces. This might be helpful to you if you need communication between components that have no parent-child relationship.
我使用过的另一种方法(除了使用事件进行通信)是使用中央组件注册表,该注册表具有对公共 API 的引用,并绑定了一个组件实例.注册表处理对组件的请求并返回其公共 API.
Another approach I have experience with (other than using events for communication), is using a central component registry that has a reference to the public API with an instance of a component bound to it. The registry handles requests for a component and returns its public API.
在 Vue.js 的上下文中,事件是我选择的武器.
In the context of Vue.js, events would by my weapon of choice.
这篇关于Vue 组件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!