Vue 组件之间常用的通信方式
- props
- 总线 eventbus
- vuex
- 自定义事件
- 关系情况
- $parent
- $children
- $root
- $refs
- provide/inject
 
- 非 prop 特性
- $attrs
- $listener
 
 
- 关系情况
	props 父->子传值 用属性
		parent
			<child :faData = '来自父亲'></child>
		child
			props:{
				faData:{
					type:String,
					default:""
				}
			}	
		子->父	 用自定义事件	
		child
			this.$emit('add',good)
		parent
			<child @add='cartAdd($event)'></child>
		
事件总线
任意两个组件之间值传递
	main.js 注册 
		Vue.prototype.$bus = new Vue()
	
	parent 
		<template>
			<child1 ></child1>
			<child2 ></child2>
		<template>
		
	child1
		this.$bus.$on('event-from-child2',msg=>{
				console.log(msg)
			})
	child2
		this.$bus.$emit('event-from-child2','some msg from child2')
$parent / $root
- 发布订阅模式,事件派发和订阅的是一个人
	parent 里 child1 和child2 通信
	
		<child1></child1>
		<child2></child2>
		
		
	child1
		mounted(){
			this.$parent.$on('event-from-child2',msg=>{
				console.log(msg)
			})
		}
	
	child2
		mounted(){
			this.$parent.$emit('event-from-child2','some msg from child2')
		}
	
$children
父组件可以通过$children 访问子组件实现父子通信
$children 拿到的是一个子组件数组,不能保证子元素顺序
	parent
		<button @click='goHome'></button>
		goHome(){
			this.$children[0].eat()
		}
		
	child1
		eat(){
			console.log('马上回')
		}
	child2
$attrs / $listeners
包含了父作用域中不作为prop被识别(且获取)的特性绑定(class 和style 除外).当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class 和 style 除外),并且可以通过v-bind = “$attrs” 传入内部组件——在创建高级别的组件时非常有用
	parent 
		<child foo='foo' @click='onClick'></child>
		onClick(){
			console.log("来自parent的回调函数处理")
		}
	child
		<p v-on='$listeners'>{{$attrs.foo}}</p>
		并未在props 中声明foo
		v-on='$listeners' 运行会被展开并监听(在parent里监听)
		
	child2
		
refs
获取子节点引用 | 访问普通的dom 元素
provide / inject 依赖注入可以跨层级传参
能够实现祖先和后代之间传值
	ancestor
		provide(){
			return {foo:'foo'}
		}
	descendant
		inject:['foo']
		可以起别名
		inject:{bar:{from:'foo'}}
点击查看更多内容
					7人点赞
										
				 评论
				共同学习,写下你的评论
评论加载中...
作者其他优质文章
					正在加载中
				
			感谢您的支持,我会继续努力的~
		扫码打赏,你说多少就多少
		赞赏金额会直接到老师账户
		支付方式
		打开微信扫一扫,即可进行扫码打赏哦
	 
                 
             
			 
					 
					