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

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

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

相关推荐
安全系统学习1 分钟前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖17 分钟前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖28 分钟前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水1 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐1 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06271 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
灿灿121381 小时前
CSS 文字浮雕效果:巧用 text-shadow 实现 3D 立体文字
前端·css
烛阴2 小时前
Babel 完全上手指南:从零开始解锁现代 JavaScript 开发的超能力!
前端·javascript
AntBlack2 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
31535669132 小时前
一个简单的脚本,让pdf开启夜间模式
前端·后端