1、子组件:DemoHello.vue

<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>

2、父组件:App.vue

<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('','')"/>

Logo

前往低代码交流专区

更多推荐