1.父组件向子组件传递数据
父组件是通过props属性给子组件通信,Prop 是你可以在组件上注册的一些自定义特性。当一个值传递给一个 prop 特性的时候,它就变成了那个组件实例的一个属性。
父组件:
<parent>
<child :child-com="content"></child> //注意这里用驼峰写法哦
</parent>
data(){
return {
content:'sichaoyun'
};
}
子组件通过props来接受数据
第一种方法
props: ['childCom']
第二种方法
props: {
childCom: String //这里指定了字符串类型,如果类型不一致会警告的哦
}
第三种方法
props: {
childCom: {
type: String,
default: 'sichaoyun'
}
}
props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值。
2.子组件向父组件传递数据
子组件通过事件向父级组件发送消息,子组件向父组件传递数据用$emit方法。
template:
<child @showbox="toshow"></child>
js:
methods:{
toshow(msg) {
this.msg2 = msg;
},
}
template:
<input @click="open" type="button" value="按钮" />
js:
methods:{
open() {
this.$emit('showbox','我是子组件数据');
//触发showbox方法,'我是子组件数据'为向父组件传递的数据
}
}
首先触发子组件实例上的事件,然后通过$emit()传递参数,监听器和要传递的数据,监听器为绑定在父组件上的方法。
3.兄弟组件之间的通信
我们可以实例化一个vue实例,相当于一个第三方
let vm = new Vue(); //创建一个新实例
组件他哥
<div @click="ge"></div>
methods: {
ge() {
vm.$emit('blur','sichaoyun'); //触发事件
}
}
组件小弟接受大哥命令
<div></div>
created() {
vm.$on('blur', (arg) => {
this.test= arg; // 接收
});
}