子组件事件传递给父组件(封装组件时常用)

封装组件时常碰到子组件的一些事件要在父组件中处理,关键词时this.$emit,

注意:他要和父组件调用子组件的方法中的一个this.$emit和this.$on区分开(这里就不太多解释可以查看:https://www.cnblogs.com/heibaiqi/p/16548029.html

子组件:

<template>
    <!-- @click="getUserInfo()": 子组件自定义事件 -->
  <div class="demo" @click="getUserInfo()">
      <h1>测试创建组件</h1>
  </div>
</template>
 
<script>
export default {
    name: 'DemoHello',
    //所有函数都写在这里面
    methods:{
        getUserInfo:function(){
            /**
             * 子组件中的事件,如果想要通知父组件,可以调用这个方法,把这个自定义事件抛出去。
             * 第一个参数是:给这个事件取一个名字,什么名字都可以,父组件想要把这个抛出的函数捕获到,就是通过取的这个名字.
             * 第二个及多个参数是:当前事件的参数,也可以不传递,也可以传递任何数据。
             */
            this.$emit("getUserInfo",123,"呵呵");
        }
    }
}
</script>
 
<style scoped>
    .demo{
        color: red;
    }
</style>

 父组件:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- 使用组件 @getUserInfo:注册自定义事件,用来捕获子组件抛出的自定义事件,并且将事件交给 test 函数进行处理-->
    <DemoHello @getUserInfo="test"/>
  </div>
</template>
 
<script>
import DemoHello from './components/DemoHello.vue';
 
export default {
  name: 'App',
  //组件注册,必须要在data函数后面,不然 data 函数里面的值不会加载到这个组件中去。
  components: {
    DemoHello
  },
  methods:{
    test:function(a,b){
        alert(a+":"+b);
    }
  }
}
</script>
 
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

注意:如果子组件抛出的事件,在父组件中不能解决,那么父组件就需要向它的父组件抛出自定义事件,一直到解决为止。

父组件向上面抛事件,有两种方式:

第一种:仿照上面子组件抛出自定义函数的写法,把上面父组件的 test 函数,修改为:

test:function(a,b){
    this.$emit("getUserInfo",a,b);
}

第二种:不写函数,直接在标签里面拿到捕获到的自定义事件后,往上抛就可以了,如下:

<DemoHello :msg="msg" @getUserInfo="$emit('','')"/>

————————————————
版权声明:本文为CSDN博主「程序搬砖员」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/java_xuetu/article/details/123389255

posted @ 2022-08-03 17:33  黑白棋学弟  阅读(306)  评论(0编辑  收藏  举报