组件之间传值通讯分为三种: 父传子、子传父、兄弟组件之间的通讯
父传子
1、props 属性传递
父组件通过自定义属性给子组件传值,子组件用props接收
//父组件
<div>
<h1>Parent</h1>
<child-one :msgToChild="msg"></child-one>
</div>
data () {
return {
msg:'i am you father'
}
}
//子组件
<div>
<h1>ChildOne</h1>
<div>接收到父元素的传值:{{msgToChild}}</div>
</div>
props: {
msgToChild: {
type: String,
}
}
2、方法传递
通过组件标签进行方法的传递,子组件
$emit
触发方法
//父组件
<child-one :msgToChild="msg" @methodToChild="showMsg"></child-one>
methods:{
/*定义方法*/
showMsg () {
alert('i am your father')
}
},
//子组件
<div>接收到父亲传来的消息:{{msgToChild}}</div>
<!--定义一个按钮用来触发方法-->
<button @click="needFatherMethod">place click me</button>
props:{
/*接收方法*/
methodToChild:{
type:Function
}
},
methods:{
/*触发方法*/
needFatherMethod () {
this.$emit('methodToChild')
}
}