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

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

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

我们可以使用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.kler.cn/a/572918.html

相关文章:

  • 项目工坊 | Python驱动淘宝信息爬虫
  • CSS设置文字渐变色样式(附带动画效果)
  • 鸿蒙5.0实战案例:基于OpenGL渲染视频画面帧
  • 网络编程之TCP协议
  • 数据结构:八大排序(冒泡,堆,插入,选择,希尔,快排,归并,计数)详解
  • CHAPTER 5 Data Class Builders
  • MWC 2025 | 移远通信大模型解决方案加速落地,引领服务机器人创新变革
  • Tripo3D使用体验
  • C语言_图书管理系统_借阅系统管理
  • E22-xxxT22D lora模块配置
  • OpenFeign 学习笔记
  • 并查集—数组实现
  • 【Linux】进程间通信 续
  • 美颜SDK架构揭秘:人脸美型API的底层实现与优化策略
  • 立体仓WMS同MES制造的协同
  • upload-labs Pass5-18 文件上传
  • 观察者模式的C++实现示例
  • 从零开始的kafka学习 (一)| 概念,Java API
  • 从vue源码解析Vue.set()和this.$set()
  • 深入浅出:UniApp 从入门到精通全指南