Vue communication between the components, from father to son parent

Reference article: https://www.cnblogs.com/yszblog/p/10135969.html

1 father to son  

  Subassemblies Vue

Parent component  

Registration subassembly

 

  • Create a sub-assembly properties in the props, the value received for transmission over the parent component
  • Registered parent component sub-assemblies
  • Adding properties in a subcomponent props created in the sub-element tag
  • We need to pass the value assigned to the property subassembly

2 pass through the value of the parent element subassembly $ EMIT

  Vue 2.1 subcomponents

   

2.2 parent component

   2.3 monitor the parent component sub-assemblies launch event name

  • Subassemblies need to somehow click event such as approach to trigger a custom event
  • The need to pass $ EMIT value as the second parameter, which value is passed as an argument in response custom event method
  • Sign subassemblies and listen to bind custom event on the child component tags in the parent assembly
In the communication, both sub-assemblies pass values ​​to the parent component to pass by value or parent component sub-assemblies, they all have one thing in common intermediate medium, the medium is the child to the parent of custom events, parent to child is props media in the property. Grasping for these two like to understand parent-child communication

The 3 brothers, father and son, sibling traditional values

With a bus ways same level components communicate
Whether it is the parent to the child to the parent or the child by value by value, it requires an intermediate medium. In fact, the same for the same level components, they also need an intermediate medium as a central event bus,
A. Let's create a central event bus, creating a eventBus.js in src / assets / under, reads as follows

eventBus we just created a new Vue instance, after it assumed the bridge of communication between components, that is the central event bus.

II. Creating a firstChild components, introduced eventBus this event bus, and then add a button and bind a click event
 
III. Let us create a secondChild components, introduced eventBus event bus, and with a p tag to display the passed value
 

我们在mounted中,监听了userDefinedEvent,并把传递过来的字符串参数传递给了$on监听器的回调函数
PS:
mounted:是一个Vue生命周期中的钩子函数,简单点说就类似于jquery的ready,Vue会在文档加载完毕后调用mounted函数。
$on:监听当前实例上的自定义事件(此处当前实例为bus)。事件可以由$emit触发,回调函数会接收所有传入事件触发函数($emit)的额外参数。

四 . 在父组件中,注册这两个组件,并添加这两个组件的标签

总结:
  • 创建一个事件总线,例如demo中的eventBus,用它作为通信桥梁
  • 在需要传值的组件中用bus.$emit触发一个自定义事件,并传递参数
  • 在需要接收数据的组件中用bus.$on监听自定义事件,并在回调函数中处理传递过来的参数

Guess you like

Origin www.cnblogs.com/bride/p/11237097.html