组件中的通信有很多种,下面我就讲讲我们常用的方式吧!
1,父组件传到子组件
- 首先,先在父组件的标签上写一个自定义属性,后面传递需要传输的数据
![这些都是自定义属性](https://img-blog.csdnimg.cn/20210521074658781.png)
- 自定义属性可以多个传递的
- 然后子组件中使用
props
来接收数据
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210521074948523.png)
- 接收完之后使用
this
就可以调用了 props
可以使用3种方法来接收数据- 第一种
props: ['childCom']
props: {
childCom: String
}
props: {
childCom: {
type: String,
default: 'sichaoyun'
}
}
2,子组件向父组件传值
- 首先,先在父组件的标签上写一个自定义事件,后面写事件
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210521080140594.png)
- 自定义属性可以多个传递的
- 然后在子组件中使用
$emit
来触发父组件的标签上的自定义事件
![在这里插入图片描述](https://img-blog.csdnimg.cn/202105210804280.png)
- 可以在触发事件的时候传递数据
3,兄弟组件传参
- 在
main.js
中创建一个空的vue实例,并命名为$bus
window.$bus=new Vue();
- 设有兄弟组件A,B。A跟B传数据
- 使用
$bus.$emit()
来传递数据 - 使用
$bus.$on()
接收数据
fun(){
$bus.$emit('abc',123)
}
fun(){
$bus.$on("abc", (msg) => {
console.log(msg);
});
}