- props
- 总线 eventbus
- vuex
- 自定义事件
- 关系情况
- $parent
- $children
- $root
- $refs
- provide/inject
- 非 prop 特性
- $attrs
- $listener
- 关系情况
props 父->子传值 用属性 parent事件总线child props:{ fadata:{ type:String, default:"" } } 子->父 用自定义事件 child this.$emit('add',good) parent
任意两个组件之间值传递
main.js 注册 Vue.prototype.$bus = new Vue() parent$parent / $rootchild1 this.$bus.$on('event-from-child2',msg=>{ console.log(msg) }) child2 this.$bus.$emit('event-from-child2','some msg from child2')
- 发布订阅模式,事件派发和订阅的是一个人
parent 里 child1 和child2 通信$childrenchild1 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 拿到的是一个子组件数组,不能保证子元素顺序
parent
goHome(){
this.$children[0].eat()
}
child1
eat(){
console.log('马上回')
}
child2
$attrs / $listeners
包含了父作用域中不作为prop被识别(且获取)的特性绑定(class 和style 除外).当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class 和 style 除外),并且可以通过v-bind = “$attrs” 传入内部组件——在创建高级别的组件时非常有用
parentrefsonClick(){ console.log("来自parent的回调函数处理") } child {{$attrs.foo}}
并未在props 中声明foo v-on='$listeners' 运行会被展开并监听(在parent里监听) child2
provide / inject 依赖注入可以跨层级传参获取子节点引用 | 访问普通的dom 元素
能够实现祖先和后代之间传值
ancestor
provide(){
return {foo:'foo'}
}
descendant
inject:['foo']
可以起别名
inject:{bar:{from:'foo'}}



