初识 Vue(18)---(非父子组件间的传值)

非父子组件间的传值

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

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>
	<meta charset="UTF-8">
	<title>非父子组件间的传值</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<child content="Dell"></child>
		<child content="Lee"></child>
	</div>	
	<script>
	Vue.component('child',{
		props:{
			content:String
		},
		template:'<div>{{content}}</div>',
		
	})

	var vm = new Vue({
		el:'#root',
		})
	</script>
</body>
</html>

输出:

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

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>非父子组件间的传值</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<child content="Dell"></child>
		<child content="Lee"></child>
	</div>	
	<script>
	//在 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',
		})
	</script>
</body>
</html>

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

  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值