【问题标题】:Use default value if prop argument is null如果 prop 参数为 null,则使用默认值
【发布时间】:2018-06-20 02:05:46
【问题描述】:
我有这个简化的头像组件:
<template>
<img :src="src">
</template>
<script>
export default {
name: 'Avatar',
props: {
src: {
type: String,
default: '/static/avatar-default.png'
}
}
}
</script>
假设我从我的 API 中获取了一些用户数据,但它不包含头像 URL。在这种情况下,我希望该组件使用默认值,但它似乎仅在将 undefined 传递给它时才有效,但 undefined 在 JSON 中无效,因此我无法从 API 响应中返回它。
有没有办法通过传入null 来实现我想要的,或者有更好的方法来处理这个问题?
【问题讨论】:
标签:
vue.js
vuejs2
vue-component
【解决方案1】:
如果src 是null 并且您希望组件处理默认值,您也可以显式传递undefined 作为prop。
<template>
<img :src="src || undefined">
</template>
【解决方案2】:
如果src 是null,我将根据src 属性值创建一个计算属性,该属性将返回默认值:
<template>
<img :src="source">
</template>
<script>
export default {
name: 'Avatar',
props: {
src: { type: String }
},
computed: {
source() {
return this.src || '/static/avatar-default.png';
}
}
}
</script>
【解决方案3】:
这应该可以解决问题:
<template>
<img :src="src || '/static/avatar-default.png'">
</template>
就个人而言,除了将 null 值强制为默认值之外,我还会保留 prop 的默认值。
据我所知,你无法通过 prop 定义实现你想要的。