父传子
1传递
<div>
<p>father</p>
<p>{{sonMsgs}}</p>
<button @click="gobother">goborther</button>
<Son @gofather ='sonMsg' :fatherMsg ='fatherMessge'></Son>
</div>
在子组件标签里传递值 :fatherMsg ='fatherMessge' fatherMessge就是想要传递的变量名
2子组件里面接收
props:['fatherMsg']
兄弟之间传值
1 创建bus.js文件
import Vue from "vue";
export default new Vue
2要传递的组件调用
gobother(){
bus.$emit('goborther',this.msg)
}
goborther是事件名
this.msg是要传递的参数
3 接收
mounted(){
bus.$on('goborther',(res) =>{
this.fathermsg =res
})
}
在如果想在dom元素一挂载拿到数据 就在mounted里拿数据
子传父
1 子组件 定义方法
gofather(){
this.$emit('gofather',this.sonMsg)
}
2 父组件接收
子组件标签里自定义事件 @gofather ='sonMsg' sonMsg就是要传递的参数3接收参数
<div>
<p>father</p>
<p>{{sonMsgs}}</p>
<button @click="gobother">goborther</button>
<Son @gofather ='sonMsg' :fatherMsg ='fatherMessge'></Son>
</div>
定义方法 对应sonMsg 函数内接收的参数就是子组件传递过来的数据
sonMsg(msg){
this.sonMsgs =msg
}