“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

In the previous article, we covered parent-child communication and parent-child communication. The details can be moved to the corresponding article:

  • Understand the basic use of Vue component communication for parent-child communication
  • Understand child parent communication of Vue component communication

Today we will look at how arbitrary components communicate with each other

Var Event = new Vue(),

The general idea is:

Triggers an event in one component and passes communication related data, and listens for the event trigger in another component and processes and receives related data.

Note that the scheduler must be written before mounted, in which case the assignment must be written before the scheduler is used.

<! DOCTYPEhtml>
<html>
<head>
	<meta charset="utf-8">
	<title>demo</title>
</head>
<body>
	<div id="app">
		<alice></alice>
		<br><br>
		<tom></tom>
	</div>

<script src="vue.js"></script>
<script type="text/javascript">	
	var Event = new Vue();
	
	Vue.component('alice', {template:'
       
My name is Alice :



I say: {{i_say}}
'
.data:function(){ return { i_say:' ',}},methods: {onChanged:function(){ Event.$emit('alice-say-something'.this.i_say);// Triggers an event and passes data. This event can be listened on other components}}}); Vue.component('tom', {template:'
My name is Tom :

Alice say: {{aliceSay}}
'
.data:function(){ return { aliceSay:' ',}},// Mounted Specifies whether the component is successfully mounted. You can listen here to see what the other components are saying. // Mounted is also called a life-cycle hook. It refers to a number of key points in the life-cycle, like a keyframe milestone. // mounted:function(){ var temp = this; Event.$on('alice-say-something'.function(data){// Note that it is the event scheduler that listens console.log(111); temp.aliceSay = data; });// Listen for events of other components}});var vm = new Vue({ el:'#app' });
</script> </body> </html> Copy the code

As shown in the code above, an event caller is used to link together the two components’ data, i_SAY and aliceSay

At the heart of any communication between components is an intermediate event scheduler that associates two pieces of data. In one component we emit events and send data, in another component we emit events and send data, in another component we listen for events and send data through ON.