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

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

我们可以使用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来接触绑定的事件

相关推荐
Jerry24 分钟前
使用 Material 3 在 Compose 中设置主题
前端
chéng ௹31 分钟前
uniapp 封装uni.showToast提示
前端·javascript·uni-app
tuokuac1 小时前
nginx配置前端请求转发到指定的后端ip
前端·tcp/ip·nginx
程序员爱钓鱼1 小时前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
万少1 小时前
鸿蒙创新赛 HarmonyOS 6.0.0(20) 关键特性汇总
前端
还有多远.2 小时前
jsBridge接入流程
前端·javascript·vue.js·react.js
蝶恋舞者2 小时前
web 网页数据传输处理过程
前端
非凡ghost2 小时前
FxSound:提升音频体验,让音乐更动听
前端·学习·音视频·生活·软件需求
吃饭最爱2 小时前
html的基础知识
前端·html
我没想到原来他们都是一堆坏人2 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python