1、父子组件通信
父组件
<father @fatherMethods="close">
<son ref='son' :fatherValue='value'></son>
</father>
private value = '我是你爸爸'; // 要传给子组件的值
// 父取子方法
private getSonMethods () {
(this.$refs.son as son).open() // 使用 ref 取到 子组件的方法 注 ref 取名 直接用类名 即可
}
// 父组件的方法
private close () {
console.log('我是父组件方法')
}
子组件
<son @click='open'></son>
@Prop({ default: 0 }) private fatherValue?: PdCAny; // 父组件用 : 加 要传的值的名字 后面接 要传的值
private created () {
// 接受来自父组件的数据
console.log( this.fatherValue ); // 输出: '我是你爸爸'
}
// 子组件的方法
private open () {
console.log('我是子组件')
}
// 子取父的方法
private getFatherMethods () {
this.$emit( 'fatherMethods' ) // 输出: '我是父组件方法'
}
2、兄弟组件通信
父组件
<father>
<brother></brother>
<sister></sister>
</father>
兄组件
<brother @click='changeRoute'>
<h1> {
{ brotherData }} </h1>
</brother>
private brotherData = ' 我是兄组件 '
private changeRoute() {
this.eventBus.$emit('changeRoute' , this.brotherData); // 发送事件 ’changeRoute‘ 准备传给 弟 组件
}
弟组件
<sister>
<h1> {
{ sisterData }} </h1>
</sister>
private sisterData = ' '
private created () {
this.eventBus.$on('changeRoute', (data:string) = > {
this.sisterData = data // this.sisterData = '我是兄组件'
})
}