Communication between different components in vue.js

  Vue.js communicates between different components (or sibling components of the same component). In simple cases, Vue recommends using an empty Vue instance as the event bus. Today I tried to make an example according to the official website.

  Example description: The host component issues commands, and 1 guard component and 2 participant components receive commands.

  Results as shown below:




  The code is relatively simple, not much explanation.
<!DOCTYPE html>
<!--
 Author: wallimn
 Blog: http://wallimn.iteye.com
 Time: 2017-11-22
 -->
<html>
<head>
    <meta charset="utf-8">
    <title>Vue event bus example</title>
    <script type="text/javascript" src="../lib/vue.js"></script>
</head>
<body>
	<div id="meetingHost">
	 	Moderator command: <select v-model="command">
	 		<option value="Meeting">Meeting</option>
	 		<option value="rest">rest</option>
	 		<option value="Close the meeting">Close the meeting</option>
	 	</select>
	 	<button type="button" @click="sendCommand">发布命令</button>
	</div>
	<hr>
	<div id="guard">
	 	Doorman received command: {{commandOfHost}}
	</div>
	
	<div id="guest">
		<meeting-guest name="张三"></meeting-guest>
		<meeting-guest name="李四"></meeting-guest>
	</div>

	<script type="text/javascript">
		var Bus = new Vue();//Event bus
		
		//host
		var viewHost = new View({
			el:'#meetingHost',
			data:function(){
				return {
					command:''
				};
	        },
	        methods:{
	            sendCommand:function(){
	            	Bus.$emit('hostCommand',this.command);
	            }
			}
		});
		
		//custom component, participant
		Vue.component('meeting-guest', {
			template: '<div>{{name}} received command: {{ commandOfHost }}</div>',
			props:['name'],
			data: function(){
				return {
					commandOfHost: ''
				};
			},
			created:function(){
				var self = this;
				Bus.$on('hostCommand',function(command){
					self.commandOfHost = command;
				});
			}
		});
		
		var vueGuest = new Vue({el:'#guest'});
		
		// doorman
		var viewGuard = new View({
			el:"#guard",
			data:function(){
				return {
					commandOfHost:''
				};
			},
			created:function(){
				var self = this;
				Bus.$on('hostCommand',function(command){
					self.commandOfHost = command;
				});
			}
		});
	</script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326199309&siteId=291194637