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

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

我们可以使用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 组件中 vc atguigu 方法

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

}

}

}

</script>

<style scoped>

.Student{

background-color: orange;

}

</style>

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

相关推荐
纽格立科技9 分钟前
DRM 发射端链路图(上)
前端·人工智能·车载系统·信息与通信·传媒
云水一下21 分钟前
Vue.js从零到精通系列(七):高级特性实战——Teleport、异步组件、自定义指令与TypeScript深度结合
前端·vue.js·typescript
qq43569470124 分钟前
Vue05
前端·vue.js
qq_4221525726 分钟前
PDF 解密工具怎么选?2026 年文档密码移除方案与注意事项
java·前端·pdf
YHHLAI29 分钟前
前端工程化调用 AI 多模态生图模型:Qwen Image Demo 实战
前端·人工智能
To_OC43 分钟前
我一直以为 Ajax 是个黑盒,直到我写了这 50 行代码
前端·后端·全栈
用户059540174461 小时前
RAG 记忆层踩坑实录:用户偏好凭空消失,我排查了 4 小时,最后用 LangChain + Chroma 搭了套自动化回归测试
前端·css
程序猿阿伟1 小时前
《Chrome隔离机制的维度落地指南》
前端·chrome
用户054324329701 小时前
AI 生成的代码怎么在前端安全预览 + 一键运行:sandbox iframe 实战 🔒
前端
ALianBlank1 小时前
一个 Unity 框架能做多少事?86 个模块 + 21 个小游戏平台
前端·后端·游戏开发