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

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

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

相关推荐
李姆斯6 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
鱼与宇9 小时前
前端Web(html+css+js+vue3)
前端
雪芽蓝域zzs11 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
研☆香11 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
东风破_11 小时前
JWT 1:从一个登录请求开始,理解 React 项目里的 API 层与 Mock
前端·后端
东风破_11 小时前
JWT 3:为什么 Token 要放进 Authorization?Axios 拦截器到底解决了什么?
前端·后端
东风破_11 小时前
JWT 5:路由守卫是什么?把整个 JWT 登录鉴权流程串起来
前端·后端
东风破_11 小时前
JWT 2:HTTP 是无状态的,为什么登录成功后还要给 Token?
前端·后端
东风破_11 小时前
JWT 4:Zustand 到底解决了什么?为什么登录状态要放进 Store?
前端·后端
IT_陈寒11 小时前
Vite动态导入差点让我秃头,原来问题出在这
前端·人工智能·后端