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

在开发中,往往一些数据确实需要从上层传递到下层:

  • 比如在一个页面中,我们从服务器请求到了很多的数据。
  • 其中一部分数据,并非是我们整个页面的大组件来展示的,而是需要下面的子组件进行展示。
  • 这个时候,并不会让子组件再次发送一个网络请求,而是直接让大组件(父组件)将数据传递给小组件(子组件)。

Vue官方提到如何进行父子组件间的通信:

  • 通过props向子组件传递数据
  • 通过事件向父组件发送消息 

 

 

 一、props的基本用法

在组件中,使用选项props来声明需要从父级接收到的数据。props的值有两种方式:

  • 方式一: 字符串数组,数组中的字符串就是传递时的名称。
  • 方式二: 对象,对象可以设置传递时的类型,也可以设置默认值等。

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-bind:cmovies="movies" :cmessage="message"></cpn>
</div>
 
<template id="cpn">
  <div>
    <p v-for="item in cmovies">{{item}}</p>
    <p> {{cmessage}}</p>
  </div>
</template>
<script>
  //父传子
  const cpn = {
    template: "#cpn",
    //props: ["cmovies","cmessage"],
    props: {
      // //1. 类型的限制
      // cmovies: Array,
      // cmessage: String
       
      // //2. 提供一些默认值,以及必传值
      cmessage: {
        Type: String,
        //当没有进行父级传值时会使用默认值
        default: "aaaaaa",
        // required 必须传的值
        required:true
      },
      cmovies: {
        Type: Array,
        //类型是对象或者数组时,默认值必须是一个函数
        default(){
          return []
        }
      }
    },
    data(){ return {}},
    methods: {}
  }
 
  const app = new Vue({
    el: "#app",
    data: {
      message: "Hellow World",
      movies: ["泰坦尼克号","海泽王","海尔兄弟"]
    },
    components: {
      cpn
    }
  });
</script>
  • 注意:在创建模板时,需要将 <template></template> 中写入一个容器,例如<div>标签;
  • 在使用驼峰标识时,在模板标签引用中需要使用 “-” 符号将大写字母区隔开,在<template>模板标签中使用组件自定义驼峰标识名称(如下图所示 :c-info 和 :c-message)
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
<div id="app">
  <cpn :c-info="info" :c-message="message"></cpn>
</div>
<template id="cpn">
  <div>
    <h2>{{ cInfo }}</h2>
    <h2>{{ cMessage }}</h2>
  </div>
</template>
<script>
  const cpn = {
    template : "#cpn",
    props: {
      cInfo: {
        Type: Object,
        default(){ return {}}
      },
      cMessage: {
        Type: String,
        default(){ return ""}
      }
    }
  }
  const app = new Vue({
    el: "#app",
    data: {
      message: "Hellow World",
      info: {
        name: "why",
        age: 18,
        height: 1.88
      }
    },
    components: {
      cpn
    }
  });
</script>

  

 

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