组件自定义事件是一种组件间通信的方式,适用于:子组件 ===> 父组件
A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
第一种方式,在父组件中:
App.vue
- <template>
- <div class="app">
-
- <Student @atguigu="getStudentName"/>
- div>
- template>
-
- <script>
- import Student from './components/Student'
-
- export default {
- name:'App',
- components:{Student},
- data() {
- return {
- msg:'你好啊!',
- studentName:''
- }
- },
- methods: {
- getStudentName(name,...params){
- console.log('App收到了学生名:',name,params)
- this.studentName = name
- }
- }
- }
- script>
-
- <style scoped>
- .app{
- background-color: gray;
- padding: 5px;
- }
- style>
-
Student.vue
- <template>
- <div class="student">
- <button @click="sendStudentlName">把学生名给App</button>
- </div>
- </template>
-
- <script>
- export default {
- name:'Student',
- data() {
- return {
- name:'张三',
- }
- },
- methods: {
- sendStudentlName(){
- //触发Student组件实例身上的atguigu事件
- this.$emit('atguigu',this.name,666,888,900)
- }
- },
- }
- </script>
-
- <style lang="less" scoped>
- .student{
- background-color: pink;
- padding: 5px;
- margin-top: 30px;
- }
- </style>
-
使用 this.$refs.xxx.$on() 这样写起来更灵活,比如可以加定时器啥的。
App.vue
- <template>
- <div class="app">
- <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
- <Student ref="student"/>
- </div>
- </template>
-
- <script>
- import Student from './components/Student'
-
- export default {
- name:'App',
- components:{Student},
- data() {
- return {
- studentName:''
- }
- },
- methods: {
- getStudentName(name,...params){
- console.log('App收到了学生名:',name,params)
- this.studentName = name
- },
- },
- mounted() {
- this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
- // this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
- },
- }
- </script>
-
- <style scoped>
- .app{
- background-color: gray;
- padding: 5px;
- }
- </style>
-
Student.vue
- <template>
- <div class="student">
- <button @click="sendStudentlName">把学生名给App</button>
- </div>
- </template>
-
- <script>
- export default {
- name:'Student',
- data() {
- return {
- name:'张三',
- }
- },
- methods: {
- sendStudentlName(){
- //触发Student组件实例身上的atguigu事件
- this.$emit('atguigu',this.name,666,888,900)
- }
- },
- }
- </script>
-
- <style lang="less" scoped>
- .student{
- background-color: pink;
- padding: 5px;
- margin-top: 30px;
- }
- </style>
-
若想让自定义事件只能触发一次,可以使用
once修饰符,或$once方法。触发自定义事件:
this.$emit('atguigu',数据)使用 this.$emit() 就可以子组件向父组件传数据
this.$off('atguigu')- this.$off('atguigu') //解绑一个自定义事件
- // this.$off(['atguigu','demo']) //解绑多个自定义事件
- // this.$off() //解绑所有的自定义事件
组件上也可以绑定原生DOM事件,需要使用native修饰符。
- <Student ref="student" @click.native="show"/>
注意:通过
this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!