首页 前端知识 Vue中的this.$emit()方法详解【父子组件传值常用】

Vue中的this.$emit()方法详解【父子组件传值常用】

2024-09-29 22:09:11 前端知识 前端哥 39 432 我要收藏

​在Vue中,this.$emit()方法用于触发自定义事件。它是Vue实例的一个方法,可以在组件内部使用。

使用this.$emit()方法,你可以向父组件发送自定义事件,并传递数据给父组件。父组件可以通过监听这个自定义事件来执行相应的逻辑。

下面是一个简单的示例,展示了如何在Vue组件中使用this.$emit()方法:项目文件夹下该组件定义路径 E:\myproject\src\components\ChildComponent\index.vue

子组件 index.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<template>

    <button @click="handleButtonClick">点击触发事件</button>

</template>

<script>

export default {

    name:'ChildComponent',

    methods: {

        handleButtonClick() {

            // 触发自定义事件,并传递数据给父组件

            this.$emit('custom-event', 'Hello, World!');

        }

    }

}

</script>

在上面的示例中,当按钮被点击时,handleButtonClick方法会被调用。在该方法中,我们使用this.$emit()方法触发了一个名为custom-event的自定义事件,并传递了字符串’Hello, World!'作为数据。

父组件可以通过监听custom-event来接收这个自定义事件,并执行相应的逻辑。例如,在父组件中可以这样监听并处理这个事件:

父组件 table.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<template>

    <el-row>

        <el-col :span="24">

            <el-card>

                <el-table...>

                        ...

                </el-table>

            </el-card>

        </el-col>

    <el-row>

    <div>

        <child-component @custom-event="handleCustomEvent"></child-component>

    </div>

</template>

// 在父组件中导入子组件

import ChildComponent from '@/components/ChildComponent'

<script>

export default {

    name: 'App',

    data() {

        return {

        }

    },

    // 注册子组件

    components: {

        ChildComponent

    },  

    methods: {

        handleCustomEvent(data) {

          // 处理自定义事件的逻辑

          console.log(data); // 输出:'Hello, World!'

        }

    }

父组件通过@custom-event监听了custom-event自定义事件,并在handleCustomEvent方法中处理了这个事件。当子组件中的this.$emit(‘custom-event’, ‘Hello, World!’)被触发时,父组件的handleCustomEvent方法会被调用,并且传递的数据’Hello, World!'会被打印出来。

注: 

通过在components选项中注册子组件,可以在父组件的模板中使用该子组件。在这个例子中,父组件可以通过以下方式在模板中使用ChildComponent:

1

2

3

4

5

<template>

  <div>

    <child-component></child-component>

  </div>

</template>

子组件在模板中使用时需要使用短横线命名法(kebab-case),而在组件定义中使用驼峰命名法(camelCase)。你可以在components选项中注册多个子组件,并在父组件的模板中使用它们。这样可以实现更好的代码组织和复用。

这就是使用this.$emit()方法在Vue中触发自定义事件的基本用法。

更多参考:

彻底明白VUE修饰符sync - 简书

Vue中的this.$emit()方法详解_vue.js_脚本之家

转载请注明出处或者链接地址:https://www.qianduange.cn//article/18759.html
标签
评论
发布的文章

JSON简介

2024-09-30 23:09:25

Node.js和npm的安装及配置

2024-09-30 23:09:02

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!