Vue组件通信 [英] Vue components communication

查看:121
本文介绍了Vue组件通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Vue组件:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆