父子组件通信
子组件给父组件传递数据
1.通过 props :父组件向子组件传递一个函数型的 props。子组件通过 props 调用这个在父组件中定义的函数来传递数据。
父组件:
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName"/>
methods: {
getSchoolName(name){
console.log('App收到了学校名:',name)
}
}
子组件:
<button @click="sendSchoolName">把学校名给App</button>
props:['getSchoolName'],
methods: {
sendSchoolName(){
this.getSchoolName(this.name)
}
},
2.通过自定义事件
2.1:父组件内自定义事件,子组件内触发这个事件并传递数据。
父组件:
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<Student @atguigu="getStudentName" @demo="m1"/>
getStudentName(name,...params){
console.log('App收到了学生名:',name,params)
this.studentName = name
},
子组件:
<button @click="sendStudentlName">把学生名给App</button>
methods: {
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
// this.$emit('demo')
// this.$emit('click')
},
2.2 父组件内定义 监听 事件,子组件内触发这个事件并传递数据。
父组件:
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Student ref="student" @click.native="show"/>
mounted() {
this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
},
子组件:
<button @click="sendStudentlName">把学生名给App</button>
methods: {
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
// this.$emit('demo')
// this.$emit('click')
},