非父子组件间的传值

常一个应用会以一棵嵌套的组件树的形式来组织:将一个大组件进行拆分

Component Tree

下图这种情况的组件间传值(父子组件间传值)

方法:父组件通过 Props 向子组件传值,子组件通过事件触发向父组件传值

下图这种情况的组件间传值(父子组件间隔代传值,也是非父子组件间传值)

方法:将第二层作为中间层,父组件(1)通过 Props 向子组件(2)传值,父组件(2)通过 Props 向子组件(3)传值,

子组件(3)通过事件触发向父组件(2)传值; 子组件(2)通过事件触发向父组件(1)传值;

下图这种情况的组件间传值(非父子组件间传值)

参照上面的方法,也可以将第1层、第2层作为中间层来实现传值,原理上可行;但极其复杂...

解决非父子组件间传值方法:1.Vue 官方提供的 Vuex 框架    2.发布订阅模式(总线机制 / Bus / 观察者模式)

案例:

<!DOCTYPE html><html lang="en"><head>	<  charset="UTF-8">	< >非父子组件间的传值</ >	<  src="./vue.js"></ ></head><body>	<div id="root">		<child content="Dell"></child>		<child content="Lee"></child>	</div>		< >	Vue.component('child',{		props:{			content:String		},		template:'<div>{{content}}</div>',			})	var vm = new Vue({		el:'#root',		})	</ ></body></html>

输出:

功能:点击 Dell 时,下面的 Lee 也变成 Dell ; 点击 Lee,上面的 Dell 也会变为 Lee;(非父子组件间传值)

<!DOCTYPE html><html lang="en"><head>	<  charset="UTF-8">	< >非父子组件间的传值</ >	<  src="./vue.js"></ ></head><body>	<div id="root">		<child content="Dell"></child>		<child content="Lee"></child>	</div>		< >	//在 Vue类上挂载 bus属性,每一个Vue的实例上都会有bus属性	Vue.prototype.bus = new Vue()	Vue.component('child',{		//子组件的 data 一定是个函数		data:function(){     //单项数据流			return{      				selfContent: this.content			}		},		props: {			content:String		},		template:'<div @click="handleClick">{{content}}</div>',		methods:{			handleClick:function(){				this.bus.$emit('change',this.selfContent)	//触发 change 事件且携带数据(content)				}		},	//监听 Bus 的改变		mounted:function(){			var this_ = this  //为解决作用域发生变化,需保持 this			this.bus.$on('change',function(msg){				this_.selfContent = msg			})		}			})	var vm = new Vue({		el:'#root',		})	</ ></body></html>

输出:(bus 总线来进行非父子组件间的传值)

  

收藏 打印