日常开发记录--父子组件通信,当父组件传的值为null或undefined时报错

本文介绍了父组件About.vue如何通过props将info属性传递给子组件Child.vue,以及如何避免在info为null或undefined时引发错误。重点在于理解Vue组件间的通信和数据传递的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父组件About.vue
<template>
  <div class="about">
    <h1>Today is not easy,</h1>
    <h1>Tomorrow is more difficult,</h1>
    <h1>But the day after tomorrow will be wonderful!</h1>
    <Child :info="info || {}"/>
  </div>
</template>

<script>
import Child from './components/Child.vue'
export default {
  components: { Child },
  data () {
    return {
      // 当info传的是null或者undefined时,控制台会报错,传空对象倒不会出错
      info: null
    }
  }
}
</script>

子组件Child.vue

<template>
  <div>{{ info.school }}</div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    info: {
      type: Object,
      required: true
    }
  },
  data () {
    return {

    }
  }
}
</script>

<style>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值