搜索文档
知识点
- 一种组件间通信的方式,适用于子组件向父组件传递数据。
- 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在 A 中)
- 绑定自定义事件有两种方式:
- 在父组件中找到子组件标签,在标签上通过 v-on 或 @ 绑定事件。
- 在父组件中给子组件设置 ref 值,在某个函数中通过
this.$ref.xxx.$on(函数名,函数回调)函数回调要么配置在methods中,要么用箭头函数,否则 this 只想会出问题。
- 触发自定义事件:
this.$emit(事件名,数据) - 解绑自定义事件:
this.$off(事件名) - 组件上可以使用原生 DOM 事件,需要使用
native修饰符。
代码
子给父传数据
父组件 App.vue
Vue<template> <div> <School></School> <Student @getStudentName="getStudentName"></Student> </div> </template> <script> import Student from './components/Student.vue' import School from './components/School.vue' export default { name: 'App', components: { Student,School }, methods: { getStudentName(e){ console.log("App 接收到的数据:",e); } }, } </script>子组件 Student.vue
Vue<template> <div class="box back"> <h5>学生姓名:{{name}}</h5> <h5>学生性别:{{sex}}</h5> <h5>学生年龄:{{age}}</h5> <button @click="returnStudentName">返回学生姓名</button> </div> </template> <script> export default { name: 'Student', data(){ return { name: 'SevenOne', sex: '男', age: 21, } }, methods: { returnStudentName(){ this.$emit('getStudentName', this.name); } }, } </script>代码解析:
- 这两段代码,我们先看一下子组件。在子组件中,代码第 6 行我们给 button 标签绑定了一个单击事件,在事件中我们通过
this.$emit()函数向父组件发射一个函数,并携带了数据。 - 在父组件中,给子组件标签绑定了由子组件发射回来的事件,并在父组件的 methods 中配置了该事件,函数的参数既是子组件传递的数据。
- 这两段代码,我们先看一下子组件。在子组件中,代码第 6 行我们给 button 标签绑定了一个单击事件,在事件中我们通过
给组件绑定原生DOM事件
父组件:App.vue
html<template> <div> <School></School> <Student @getStudentName="getStudentName" @click.native="demoClick"></Student> </div> </template> <script> import Student from './components/Student.vue' import School from './components/School.vue' export default { name: 'App', components: { Student,School }, methods: { getStudentName(e){ console.log("App 接收到的数据:",e); }, demoClick(){ console.log("demoClick 被调用"); } }, } </script>代码第四行,为子组件绑定单击事件,在事件后面加上了
.netvie事件修饰符,如果不加修饰符,程序回认为我们给 Student 组件绑定了一个名为 click 的自定义事件。
