当前位置: 首页 > news >正文

前端基础之组件自定义事件

我们可以通过使用给组件绑定事件,当组件触发该事件时,就能进行值得返回

我们可以使用v-on属性来给子组件绑定自定义事件,此时该事件就会存在vc中,然后通过this.$emit来触发绑定的事件,

这样就能实现不需要app.vue来给子组件传参的复杂形式来实现方法的调用

也可以使用ref来绑定事件,并且ref更为灵活,并且能实现延迟绑定等功能

App.vue

<template>

  <div class="app">

    <h1>{{msg}}</h1>

    <!-- 通过v-on给子组件绑定一个事件 -->

    <!-- <student v-on:atguigu="sendStudentName"></student> -->

     

    <student ref="student"></student>

    <school :getSchoolName="getSchoolName"></school>

   

    <hr>

  </div>

</template>

<script>

import Student from './components/Student.vue'

import School from './components/School.vue'

export default {

  name: 'App',

  components: { Student, School },

  data(){

    return{

       msg:"hello"

    }

  },

  methods:{

    getSchoolName(name){

      console.log('App收到了学校名',name)

    },

    sendStudentName(name){

      console.log('sendStudentName事件被触发了',name)

    }

  },

  mounted(){

   setTimeout(()=>{

    this.$refs.student.$on('atguigu',this.sendStudentName)

   },3000)

  }

}

</script>

<style>

/* 配置全局样式 */

.app {

background-color: gray;

}

</style>

Student.vue

<template>

  <div class="Student">

    <h2  >学生姓名:{{name}}</h2>

    <h2>学生性别:{{sex}}</h2>

    <button @click="sendStudentName">点击获取学生姓名</button>

  </div>

</template>

<script>

export default {

    name:'Student',

   

    data(){

        return{

          name:'李四',

         sex:""

        }

    },

    methods:{

      sendStudentName(){

        //使用$emit来触发Student组件中vcatguigu方法

        this.$emit('atguigu',this.name)

      }

    }

}

</script>

<style scoped>

.Student{

  background-color: orange;

}

</style>

使用$off来接触绑定的事件

http://www.dtcms.com/a/52094.html

相关文章:

  • Web服务器配置
  • PX4中的DroneCAN的实现库Libuavcan及基础功能示例
  • 利用行波展开法测量横观各向同性生物组织的生物力学特性|文献速递-医学影像人工智能进展
  • Web3 的未来:去中心化如何重塑互联网
  • 美颜SDK架构揭秘:人脸美型API的底层实现与优化策略
  • DeepSeek+Graphrag检索增强
  • 【0010】Python流程控制结构-分支结构详解
  • [machine learning] MACS、MACs、FLOPS、FLOPs
  • 第三章 指令系统
  • K8s控制器Deployment详解
  • 小程序是否支持SSE
  • 《量子潮涌下,DataWorks中AI模型训练框架的变革征途》
  • 极狐GitLab 17.9 正式发布,40+ DevSecOps 重点功能解读【二】
  • C#批量压缩并上载CSV数据文件到Box企业云盘
  • 统一数据返回格式
  • IDEA入门及常用快捷键
  • AI-Deepseek + PPT
  • 用Python之requests库调用大模型API实现多轮对话
  • Vulnhub-Hackme靶机
  • centos7服务器 Java和Hadoop安装教程,用VMware和finalshell
  • 2025东方财富笔试考什么?cata能力测评攻略|答题技巧真题分享
  • 浙江省一体化数字资源系统(IRS)介绍(七个方面展开)
  • PHP之字符串拼接
  • vscode远程ssh链接服务器
  • 内网环境下如何快速下载大模型
  • 【Python爬虫】利用代理IP爬取跨境电商AI选品分析
  • 3.4刷题
  • RS485总线为什么要加终端电阻?
  • Blazor-路由模板(下)
  • 如何在Spring Boot中读取JAR包内resources目录下文件