I'm attempting to bind a background image from an external data source through Vue.js. This is what the code looks like:
<div class="image-box border"
:style="{ background: `url(`+ item.image +`) no-repeat center` }"
style="width: 220px; height: 220px">
I've also tried this:
<div class="image-box border"
:style="{ 'backgroundImage': 'url(' + item.image + ')' }">
This is what the url reads like in the app with no error:
background-image: url("http://localhost:8080/assets/images/shoe-1.png");
Any help is appreciated!
Full code:
component -
<template>
<div class="product-card-box border">
<div class="image-box border"
:style="{ background: `url(`+ item.image +`) no-repeat center` }"
style="width: 220px; height: 220px">
<!-- :style="{ 'backgroundImage': 'url(' + item.image + ')' }"> -->
</div>
<div class="info-box border">
<div class="color-info product-info bold">{{item.colors.length}} color</div>
<div class="product-name">
<div class="product-info bold">{{item.name}}</div>
<div class="product-info sub-info">{{item.gender}}'s Shoe</div>
</div>
<div class="product-price">
<div class="product-info sub-info">${{item.price}}</div>
</div>
</div>
</div>
</template>
data -
const data = [
{
name: 'SNKR 001',
gender: 'Men',
price: 100,
sport: 'running',
width: 'Wide',
colors: ['black', 'white', 'green', 'pink'],
sizes: [3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 14, 15],
image: '../assets/images/shoe-1.png'
},
{
name: 'SNKR 002',
gender: 'Men',
price: 100,
sport: 'running',
width: 'Wide',
colors: ['black', 'white', 'green', 'pink'],
sizes: [3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 14, 15],
image: '../assets/images/shoe-1.png'
}
];
export default data;
Consider just having one style
object. Also, does it have to be a background image? I'm sure you could accomplish the same thing with an img
and a class and just making it object-fit
.
<div id="app">
<div :style="{
width: '200px',
height: '200px',
'background-image': `url(${backgroundImage}`,
}"/>
</div>
new Vue({
el: "#app",
data: {
backgroundImage: 'http://picsum.photos/g/1200/400?image=30',
},
})
Check this fiddle for the object-fit
solution https://jsfiddle.net/caseyjoneal/b5r8fvjq/73/
在data[]
,使用require(path)
以便在模板中正确解析路径:
image: require('../assets/images/shoe-1.png')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.