从外部源绑定图像

问题描述 投票:0回答:2

我正在尝试通过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 + ')' }">

这是url在应用程序中读取的内容,没有错误:

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;
javascript css vue.js data-binding
2个回答
0
投票

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

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

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/

© www.soinside.com 2019 - 2024. All rights reserved.