我有一个区域,人们可以上传自己的用户图像。但是,如果没有,我想显示一个默认值。
经过一番谷歌搜索后,我发现我可以通过以下操作来做到这一点-
<img :src="creatorImage" @error="defaultAvatar">
但是,我不确定如何创建一种方法来将正确的(默认)图像传递到其中。
答案 0 :(得分:0)
我建议为此创建一个组件,因为这听起来像是将在更多地方使用的东西。
组件
Vue.component('img-with-default', {
props: ['defaultImg'],
data: function () {
return {
defaultAvatar: this.defaultImg || 'https://cdn0.iconfinder.com/data/icons/crime-protection-people/110/Ninja-128.png'
}
},
computed:{
userImage: function() {
if(this.uploadedImg != null) {
return this.uploadedImg;
} else {
return this.defaultAvatar;
}
}
},
template: '<img :src="userImage">'
})
使用该组件将
HTML
<div id="editor">
<img-with-default></img-with-default>
<img-with-default default-img="https://cdn3.iconfinder.com/data/icons/avatars-15/64/_Ninja-2-128.png" ></img-with-default>
</div>
JS
new Vue({
el: '#editor'
})
有了它,您将拥有默认图像。
如果需要,可以创建一个组件,以显示通过的img src或默认组件。
组件
Vue.component('img-with-default', {
props: ['imgSrc'],
data: function () {
return {
imageSource: this.imgSrc || 'https://cdn0.iconfinder.com/data/icons/crime-protection-people/110/Ninja-128.png'
}
},
template: '<img :src="imageSource">'
})
并使用它
HTML
<div id="editor">
<img-with-default></img-with-default>
<img-with-default img-src="https://cdn3.iconfinder.com/data/icons/avatars-15/64/_Ninja-2-128.png" ></img-with-default>
</div>
答案 1 :(得分:0)
我使用计算属性来完成此操作,例如:
3R05ST75086