vue中父组件向子组件传递数据(props配置)

一、介绍案列

在Vue中,父组件向子组件传递信息的常见方式是通过props属性。父组件可以在子组件中定义props属性,并将需要传递的信息作为props的值。

在父组件中,可以使用v-bind指令将数据绑定到子组件的props属性上。例如:

<template>
  <div>
    <child-component :message="parentMessage"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Hello from parent component'
    };
  }
};
</script>

在子组件中,可以通过props选项定义需要接收的属性。例如:

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      required: true
    }
  }
};
</script>

通过上述代码,父组件向子组件传递了名为message的属性,并在子组件中通过{{ message }}插值表达式来显示接收到的值。

请注意,父组件中的props属性和子组件中的props选项需要名称一致才能成功传递数据。

二、props的三种配置方法

//简单接受,不能限制接受类型
  props:['msg','age']

  //可以限制接受类型
   props:{
     msg:String,
     age:Number,
   }

  //可以限制接受类型,并且规定是否必须传入,与设置默认值
  props: {
    msg: {
      //限制类型
      type: String,
      //设置是否必传
      require: true,
    },
    age: {
      type: Number,
      //设置默认值
      default: 20,
    },
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值