Use the bus bus in vue to pass values between non-parent-child components

Use the bus bus to pass values ​​between siblings, fathers, ancestors, and descendants 

Principle: Create a bus attribute in the Vue prototype, so that each component (instance) has this attribute

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>bus总线</title>
//这里自行引入 vue
		<script src="js/vue221.js"></script>
	</head>
	<body>
		<template id="zzb1">
			<div>我是zzb1 <button @click="changeCount()">传值</button></div>
		</template>
		<template id="zzb2">
			<div>
				我是zzb2
				<p>{
   
   {count}}</p>
			</div>
		</template>
		<div id="app">
			<zzb1></zzb1>
			<zzb2></zzb2>
		</div>
		<script>
			//操作zzb1 改变zzb2中内容
			//非父子关系,无法直接使用props和emit
			//bus总线:在整个Vue原型中添加一个监听
			//vuex
			Vue.prototype.bus = new Vue(); //1.在Vue原型中 创建一个bus属性 ,挂载一个新的vue实例  做监听和事件响应
			Vue.component("zzb1", {
				template: "#zzb1",
				data() {
					return {
						count: 2
					};
				},
				methods: {
					changeCount() {
						//2-触发一个事件响应 去更改zzb2,中的值
						//利用bus属性添加一个对应的响应
						this.bus.$emit("fun", this.count);
					}
				}
			});
			//3-在zzb2创建完成添加一个bus监听 : mounted中添加监听
			Vue.component("zzb2", {
				template: "#zzb2",
				data() {
					return {
						count: 1
					};
				},
				methods: {
					change() {
						console.log(1);
					}
				},
				mounted() {
					// console.log("zzb2创建 完成")
					//箭头函数  内部this指向 用于等于其产生环境
					// let that=this
					this.bus.$on("fun", (count) => {
						//this对应是 this.bus
						console.log(this);
						this.count = count;
					});
				}
			});
			let vm = new Vue({
				el: "#app"
			});
		</script>
	</body>
</html>

Guess you like

Origin blog.csdn.net/m0_65450343/article/details/126236330
Recommended