1.问题
父组件中使用自定义的子组件hello
,现在传递了两个参数:
<hello :items="languages" :unit="num"></hello>
其中num
在父组件的data
字段指定具体数值
如果不指定:unit="num"
,子组件内该怎样判断是否传入了相应的props
变量unit
?
2.代码
子组件hello
代码:
<template>
</div id="hello">
<ul v=for="item in items">
{{item}}
</ul>
<p>unit:{{unit}}</p>
</div>
</template>
<script>
export default {
props: ['items', 'unit']
}
</script>
3.解决方法
考虑到有些props
变量有默认值,有些没有,需要这样写:
props: {
items: { // 必须提供字段
required: true
},
unit: { // 可选字段,有默认值
default: 3
}
}