组件自定义事件——绑定
子组件给父组件传数据
App.vue
<!--App组件结构--> <template> <div> <!--通过父组件给子组件传递函数类型的props实现:子给父传递数据--> <School :getSchoolName="getSchoolName"></School> <!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据--> <Student @atguigu="getStudentName"></Student> </div> </template> <script> import Student from './components/Student.vue' export default{ name:'App', components:{ Student,School }, methods:{ getSchoolName(name){ console.log('App收到了学校名',name) }, getStudentName(name){ console.log('App收到了学生名',name) } } } </script>
School.vue
<template> <div> <h2>学校姓名:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="sendSchoolName">点击把学校名给App</button> </div> </template> <script> export default{ name:'School', props:['getSchoolName'], data(){ return{ name:'尚硅谷', address:'北京' } }, methods:{ sendSchoolName(){ this.getSchoolName(this.name) }} }, </script>
Student.vue
<template> <div> <h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{sex}}</h2> <button @click="sendStudentName">点击把学生名给App</button> </div> </template> <script> export default{ name:'Student', data(){ return{ name:'张三', age:18 } }, methods:{ sendStudentName(){
<!--触发Student组件实例身上的atguigu事件--> this.$emit('atguigu',this.name) }} }, </script>

浙公网安备 33010602011771号