Vue学习(十五)组件的自定义事件

本文深入探讨Vue组件的自定义事件,包括理解其作为子组件向父组件通信的机制,常见使用场景,如子组件触发事件并传递数据给父组件。详细介绍了如何绑定、触发、解绑自定义事件,以及在组件上绑定原生DOM事件时的注意事项。通过TodoList案例,展示了App、MyHeader和MyFooter组件间自定义事件的应用。
摘要由CSDN通过智能技术生成

组件的自定义事件

组件自定义事件,在父组件给子组件传入的自定义事假,事件回调写在父组件中。子组件中触发自定义事件,并且传送数据给父组件

理解

一种组件间的通讯方式,适用于子组件向父组件传递数据

使用场景

子组件给父组件传数据,在父组件中给子组件绑定自定义事件(事件的回调在父组件中)

绑定自定义事件

  1. 第一种写法:在父组件中写 <Demo @组件名称="回调函数名称" /><Demo v-on:组件名称="回调函数名称" />
  2. 第二种写法:在父组件中写:
<Demo ref="demo">
......
// 配置mounted函数
mounted() {
   
    this.$refs.demo.$on("组件名", 回调函数名);
}
  1. 使用once修饰符或 $once方法,使组件自定义事件只触发一次

触发自定义事件

在子组件中使用 this.$emit("组件名", 数据)

解绑自定义事件

在子组件中使用 this.$off("组件名")解绑一个,this.$off(["组件名1", "组件名2", ...])解绑多个,this.$off()解绑全部

组件上绑定原生DOM事件

需要使用修饰符 native

注意

通过this.$refs.demo.$on("组件名", 回调函数名);绑定自定义事件,回调最好配置在methods中,要么用箭头函数**,否则会出现this指向问题

App组件

<template>
  <div class="app">
    <h1>{
   {
   msg}}{
   {
   studentName}}</h1>
    <!-- 通过父组件给子组件传递函数类型的props实现 子给父传递数据 -->
    <School :getSchoolName="getSchoolName" />
    <hr>
    <!-- 通过父组件给子组件绑定一个自定义组件实现 子给父传递数据 (第一种写法,使用v-on:-->
    <!-- <Student v-on:atguigu="getStudentName" /> -->
    <!-- <Student @atguigu="getStudentName" @demo="m1" /> -->

  <!-- 通过父组件给子组件绑定一个自定义组件实现 子给父传递数据 (第二种写法,使用ref) -->
    <Student ref="student" @click.native="show"/>
    
  </div>
</template>

<script>
    // 引入School组件
    import School from './components/School.vue'
    import Student from './components/Student.vue'
    
    export default {
   
        name: "App",
        // 注册组件
        components: {
   Student, School},
        data() {
   
          return {
   
            msg: "你好啊!",
            studentName: ''
          }
        },
        methods: {
   
          getSchoolName(name) {
   
            console.log("App 收到了学校名称:" , name)
          },
          getStudentName(name) {
   
            console.log('App 收到了学校名称:', name);
            this.studentName = name;
          },
          m1() {
   
            console.log("自定义事件demo被触发了")
          },
          show() {
   
            alert("123");
          }
        },
        mounted() {
   
          // 绑定自定义事件
          this.$refs.student.$on("atguigu", this.getStudentName);
          /* setTimeout(()=> {
            this.$refs.student.$on("atguigu", this.getStudentName);
          }, 3000); */
        },
    }
</script>

<style>
  .app {
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值