1.父传子
props属性
//children
props:{msg:String}
//parent
<HelloWorld :msg="welcome to vue">
引用refs
//parent 子组件生成后mounted 才可以拿到 最好DOM操作的时候使用
<HelloWorld ref="hw"/>
this.$refs.hw.xx = 'xxx'
子元素children
//parent
//当前实例的直接子组件。需要注意 $children 并不保证顺序,因为$children是根据你页面加载组件
//的顺序去确定子组件在 $children数组中的顺序,也不是响应式的。如果你发现自己正在尝试使用
//$children 来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。
this.$children[0].xx = xxx
2.子传父
//child 事件谁派发 谁监听
this.$emit('add',good)
//parent
<Cart @add="cartAdd($event)"></Cart>
父组件 $parent
//parent
mathed(){
change(aa){
console.log(aa)
}
}
//child
Vue.component('child',{
props:['aaa'],
template:"<input @click='childfun' type='text'>",
methods:{
childfun:function(){
this.$parent.change1(1111)
};//触发父级事件
}
}
});
3.兄弟组件传值
通过共同的组件搭桥 root
//兄弟1
this.$parent.$on('change',(e)=>{ console.log(e) })
//兄弟2
this.$parent.$emit('change','info')
通过event bus
// main.js
Vue.prototype.$bus = new Bus()
//兄弟1
$bus.$emit('change','info')
//兄弟2
$bus.$on('change',(e)=>{ console.log(e)})
祖先和后代之间
由于嵌套层数太多,传递props不切实际,vue提供来 provide/inject Api完成改任务
//祖先
provide(){
return {foo:'foo'; changeFoo:()=>{ this.foo = 'foo2'}}
}
//子孙 注入
inject:['foo','changeFoo']