二十、父子组件的通信(子组件向父组件传递数据)

props用于父组件向子组件传递数据,还有一种比较常见的是子组件传递数据或事件到父组件中。

这个时候,我们需要使用自定义事件来完成。

■什么时候需要自定义事件呢?

  • 当子组件需要向父组件传递数据时,就要用到自定义事件了。
  • 我们之前学习的v-on不仅仅可以用于监听DOM事件,也可以用于组件间的自定义事件。

■自定义事件的流程:

  • 在子组件中,通过$emit()来触发事件。
  • 在父组件中,通过v-on来监听子组件事件。
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<div id="app">
  <!-- <cpn v-on:itemclick=""></cpn> -->
  <cpn @itemclick="cpnClick"></cpn>
</div>
 
<!-- 子组件模板 -->
<template id="id_cpn">
  <div>
    <button v-for="item in categories" @click="itemClick(item)">
      {{item.name}}
    </button>
  </div>
</template>
 
<script>
  const cpn = {
    template: "#id_cpn",
    data() {
      return {
         categories: [
           {id: 'aaa', name: "热门推荐"},
           {id: 'bbb', name: "手机数码"},
           {id: 'ccc', name: "家用家电"},
           {id: 'ddd', name: "电脑办公"},
        ]
      }
    },
    methods: {
      itemClick(item){
        //子组件发射事件:自定义事件
        this.$emit("itemclick",item);
      }
    }
  }
 
  const app = new Vue({
    el: "#app",
    data: {
      message: "Hellow World",
      info: {name: "why",age: 18,height: 1.88}
    },
    components:{
      cpn:cpn
    },
    methods: {
      cpnClick(item){
        console.log(item);
      }
    }
  });
</script>

  

posted @   搬砖工具人  阅读(147)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示