1一种组件间通信的方式,适用于:子组件 ===> 父组件
2使用场景:子组件想给父组件传数据,那么就要在父组件中给子组件绑定自定义事件(事件的回调在A中)
3绑定自定义事件

第一种方式,在父组件中<Demo @事件名="方法"/>或<Demo v-on:事件名="方法"/>
第二种方式,在父组件中this.$refs.demo.$on('事件名',方法)
<Demo ref="demo"/>
......
mounted(){
   this.$refs.demo.$on('atguigu',this.test)
}

若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法
注意:通过this.$refs.xxx.$on('事件名',回调函数)绑定自定义事件时,回调函数要么配置在methods中,要么用箭头函数,否则 this 指向会出问题(箭头函数没有this,会向外找,找到monted( ),this就是vm)

绑定事件

三种子传父的方法
APP.VUE

<template>
    <div>
        <h1 class="title">你好啊</h1>
        <School :getSchoolName="getSchoolName"/>
        <Student ref="student"/>
    </div>
</template>

<script>
    import Student from './components/Student'
    import School from './components/School'

    export default {
        name:'App',
        components:{School,Student},
        methods:{
            getSchoolName(name){
                console.log("收到了学校名字",name)
            },
            getStudentName(name){
                console.log("我被调用了",name);
            },
        },
        mounted(){
            setTimeout(()=>{
                console.log("开始调用钩子")
                this.$refs.student.$once('atguigu',this.getStudentName)
            },3000)
        }
    }
</script>

<style scoped>
    .title{
        color: red;
    }
</style>

School.vue

<template>
    <div class="demo">
        <h2 class="title">学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="sendSchoolName">把学校名称给app</button>
    </div>
</template>

<script>
    export default {
        name:'School',
        props:['getSchoolName'],
        data() {
            return {
                name:'尚硅谷atguigu',
                address:'北京',
            }
        },
        methods:{
            sendSchoolName(){
                this.getSchoolName(this.name)
            }
        }
    }
</script>

<style scoped>
    .demo{
        background-color: skyblue;
    }
</style>

Student.Vue

<template>
    <div class="demo">
        <h2 class="title">学生姓名:{{name}}</h2>
        <h2 class="atguigu">学生性别:{{sex}}</h2>
        <button @click="sendSchoolName">把学生名称给app</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data() {
            return {
                name:'张三',
                sex:'男'
            }
        },
        methods:{
            sendSchoolName(){
                // 爆发student组件实例身上的wssj 父传子案例
                this.$emit('atguigu',this.name)
            }
        },
        

    }
</script>

<style lang="less" scoped>
    .demo{
        background-color: pink;
        .atguigu{
            font-size: 40px;
        }
    }
</style>

解绑

只适用于解绑一个自定义事件。

<button @click="hdUnbind">解绑事件</button>

hdUnbind(){
    this.$off("atguigu");
}

xAr6aR.png