34-Vue脚手架-组件的自定义事件(使用自定义事件优化Todo-List案例)

发布时间 2023-10-30 18:04:10作者: 马铃薯1

组件的自定义事件

1.一种组件间通信的方式,适用于 子组件 ===> 父组件(这里也可以使用 props 传递数据进行实现)

2.使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)

3.绑定自定义事件:

1)第一种方式,在父组件中

<!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用v-on 或 @)-->
<!--<Student v-on:malingshu="getStudentName"></Student>-->
<Student @malingshu="getStudentName" @demo="m1"></Student>

...
    
methods:{
    getStudentName(name){
        console.log("APP收到了学生的名字:", name)
        this.msg = name
    }  
}

2)第二种方式,在父组件中

<!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref属性)-->
<!--ref 在组件标签上获取的是组件实例对象-->
<!--<Student ref="student"></Student>-->

...
    
methods:{
    getStudentName(name){
        console.log("APP收到了学生的名字:", name)
        this.msg = name
    }  
},
mounted(){
    // 获取方式:this.$refs.xxx
    // this.$refs.student.$on 绑定自定义事件
    this.$refs.student.$on("malingshu", this.getStudentName)

    // this.$refs.student.$once 绑定自定义事件(一次性)
    // this.$refs.student.$once("malingshu", this.getStudentName)
}

3)若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法