父子组件通信
父组件通过props
向子组件传递数据
props
只能是父组件向子组件进行传值,父组件数组更新,子组件也会随之更新props
可以传递一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以传递一个函数。props
属性名规则:如果你在props
中使用驼峰形式,模板中需要短横线的形式
// 父组件
<template>
<div>
<son :msg="infoData" :fn="myFunction"></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
name: 'father',
data(){
return {
infoData: '我是父组件的数据'
}
},
methods:{
myFunction(){
console.log("父组件")
}
},
components:{
son
}
}
</script>
// 子组件
<template>
<div>
<p>{{msg}}</p>
<button @click="fn">触发父组件传递过来的方法</button>
</div>
</template>
<script>
export default{
name: "son",
props: ["msg", "fn"]
}
</script>
也可以对props验证
<script>
export default{
name: "son",
props: {
msg: {
type: String,
required: true
},
fn: {
type: Function,
default: ()=>{}
}
}
}