父子组件通信——父传子props

  在父组件与子组件中,为了实现父子组件之间的通信,需要使用props,来实现父组件中的内容被子组件所使用。在子组件中使用props来进行与父组件之间的通信。
  在使用组件时通过绑定props中定义的变量与父组件中的属性,实现父组件的属性传递到子组件,子组件就可以使用父组件的属性了。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>父传子组件props</title>
</head>
<body>
<div id="app">
  <cpn :c-foods="foods" :c-message="message"></cpn>
</div>
<template id="cpn">
  <div>
    <ul>
      <li v-for="item in cFoods">{{item}}</li>
    </ul>
    <h2>{{cMessage}}</h2>
  </div>
</template>
<script src="js/vue.js"></script>
<script>
  const cpn = {
    template: '#cpn',
    props: {
      'cFoods': {},
      'cMessage': {}
    },
    data() {
      return {};
    }
  }
  const app = new Vue({
    el: '#app',
    data: {
      foods: ['回锅肉', '糖醋里脊', '鱼香肉丝', '糖醋鲤鱼'],
      message: '欢迎来到本系统'
    },
    components: {
      cpn
    }
  })
</script>
</body>
</html>

在这里插入图片描述
  对于props来说,可以对其进行类型限制、提供默认值

类型限制

props: {
      'cFoods': Array,
      'cMessage': String
    }

提供默认值

'cMessage': {
        type: String,
        default: '1234567'
      }

必须传值

'cMessage': {
        type: String,
        default: '1234567',
        required: true
      }

类型为对象或数组

  当类型为对象(Object)或者数组(Array)时,默认值必须为函数,否则会报错

'cMessage': {
        type: Array,
        default() {}
      }

  当props中的变量使用驼峰命名法时,在调用组件时,若使用驼峰命名法进行绑定时,系统不会识别,所以在调用组件时,绑定时使用“-”。

<div id="app">
  <cpn :c-foods="foods" :c-message="message"></cpn>
</div>

props: {
      'cFoods': Array,
      'cMessage': {
        type: Array,
        default() {}
      }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值