绑定来自外部来源的图片

时间:2019-03-04 23:47:09

标签: javascript css vue.js data-binding

我正在尝试通过Vue.js绑定来自外部数据源的背景图像。代码如下所示:

<div class="image-box border"
            :style="{ background: `url(`+ item.image +`) no-repeat center` }" 
            style="width: 220px; height: 220px">

我也尝试过:

<div class="image-box border" 
            :style="{ 'backgroundImage': 'url(' + item.image + ')' }">

这是该网址在应用中的显示,没有错误:

background-image: url("http://localhost:8080/assets/images/shoe-1.png");

感谢您的帮助!

完整代码:

组件-

<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>

数据-

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;

2 个答案:

答案 0 :(得分:0)

考虑只有一个style对象。另外,它一定是背景图片吗?我相信您可以使用img和一个类并仅使它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',
  },
})

检查此小提琴是否有object-fit解决方案https://jsfiddle.net/caseyjoneal/b5r8fvjq/73/

答案 1 :(得分:0)

data[]中,使用require(path),以便在模板中正确解析路径:

image: require('../assets/images/shoe-1.png')