(1)父组件传递数据给子组件
父组件使用prop属性,向子组件传参
<div id="app">"
<my-com :title="title" msg="hello"></my-com>
</div>
子组件接受参数
let component = {
props: ['title','msg'],
}
(2) 子组件向父组件传递数据
子组件向父组件传参
<div id="app">"
<my-com @son-handler="fatherHandler" msg="hello"></my-com>
</div>let component = {
data() {
return {
comMsg: '我是子组件数据'
}
},
template:`
<div>
<button @click='clickHandler'>发送事件</button>
</div>
`,
methods: {
clickHandler() {
this.$emit('son-handler', this.comMsg)
}
}
}new Vue({
el:'#app',
data: {
fatherDate: ''
},
methods: {
fatherHandler(val) {
// val就是子组件发送事件时,携带的参数this.comMsg
this.fatherDate = val
}
},
components: {
myCom: component
}
})
(3)单向数据流(数据更改的方向)
父级的prop数据的更新,会向下流动到子组件中,反过来不行
父组件能够修改子组件中的数据,而子组件不能直接修改父组件中的数据
作用:防止子组件意外变更状态,会影响父组件中的状态或者数据