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

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

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

相关推荐
南囝coding4 分钟前
100% 用 AI 做完一个新项目,从 Plan 到 Finished 我学到了这些
前端·后端
qiao若huan喜17 分钟前
10、webgl 基本概念 + 坐标系统 + 立方体
前端·javascript·信息可视化·webgl
前端一课44 分钟前
Vue3 的 Composition API 和 Options API 有哪些区别?举例说明 Composition API 的优势。
前端
用户47949283569151 小时前
都说node.js是事件驱动的,什么是事件驱动?
前端·node.js
晴殇i1 小时前
前端架构中的中间层设计:构建稳健可维护的组件体系
前端·面试·代码规范
申阳1 小时前
Day 7:05. 基于Nuxt开发博客项目-首页开发
前端·后端·程序员
Crystal3281 小时前
App端用户每日弹出签到弹窗如何实现?(uniapp+Vue)
前端·vue.js
摸着石头过河的石头1 小时前
Service Worker 深度解析:让你的 Web 应用离线也能飞
前端·javascript·性能优化
用户4099322502121 小时前
Vue 3中watch侦听器的正确使用姿势你掌握了吗?深度监听、与watchEffect的差异及常见报错解析
前端·ai编程·trae
1024小神1 小时前
Xcode 常用使用技巧说明,总有一个帮助你
前端