我正在尝试构建一个vue.js前端,并且该设计要求使用动态背景图像的100%宽度图块,该图像将沿着其余内容传递到页面。我已经将有效负载传递给渲染每个图块的组件,但我需要为每个图块渲染背景图像。我还需要提一下,图像实际上是每个图块需要为3个断点中的每一个渲染的3个图像。到目前为止,我能够使用:style="'background-image: url(' + backgroundImage + ')'"
传递一个图像,但这只为每个图块提供一个图像。我的问题是,每个图块传递所有3个图像并正确渲染它们的最佳方法是什么?
我在网上听说我应该使用srcset并将所有3传递给<img>
标签,并使用CSS将该图像作为背景,但这似乎是非正统的。
是否有一种更优雅的方式来处理vue.js中可重用组件中的响应式背景图像?
首页
<template>
<div class="Home">
<HomePageTile v-for="tile in tiles" :key="tile.title" :tile-title="tile.title" :tile-desc="tile.description" :tile-type="tile.position" :background-image="tile.backgroundImage"/>
</div>
</template>
<script>
import HomePageTile from '@/components/HomePageTile'
import tileImage1 from '@/assets/optimized/image1.jpg'
import tileImage2 from '@/assets/optimized/image2.jpg'
import tileImage3 from '@/assets/optimized/image3.jpg'
import tileImage4 from '@/assets/optimized/image4.jpg'
export default {
name: 'Home',
components: {
HomePageTile: HomePageTile
},
data () {
return {
tiles: [
{
title: 'Title 1',
description: 'Content 1',
position: 'right',
backgroundImage: tileImage1
}, {
title: 'Title 2',
description: 'Content 2',
position: 'right',
backgroundImage: tileImage2
}, {
title: 'Title 3',
description: 'Content 3',
position: 'right',
backgroundImage: tileImage3
}, {
title: 'Title 4',
description: 'Content 4',
position: 'right',
backgroundImage: tileImage4
}
]
}
}
}
</script>
平铺组件
<template>
<div :class="tilePosition(tileType)" :style="'background-image: url(' + backgroundImage + ')'">
<template v-if="tileType">
<div class="home-page-tile--container home-page-tile--container__with-desc">
<h2 class="home-page-tile--container--title">{{ tileTitle }}</h2>
<p class="home-page-tile--container--description">{{ tileDesc }}</p>
</div>
<div class="home-page-tile--call-to-action" v-if="callToAction">
<p class="home-page-tile--call-to-action--text">{{ callToAction.text }}</p>
<Button class="home-page-tile--call-to-action--button" :button-route="callToAction.buttonPath" :button-text="callToAction.buttonText" :button-style="callToAction.buttonStyle" />
</div>
</template>
<template v-else>
<div class="home-page-tile--container">
<h2 class="home-page-tile--container--title">{{ tileTitle }}</h2>
<Button :button-route="buttonPath" :button-text="buttonText" button-style="pill"/>
</div>
</template>
</div>
</template>
<script>
import Button from './Button'
export default {
name: 'HomePageTile',
props: {
tileType: String,
tileTitle: String,
tileDesc: String,
backgroundImage: String,
buttonText: String,
buttonPath: String,
callToAction: Object
},
components: {
Button: Button
},
data () {
return {
tilePosition: function (el) {
if (el) {
return 'home-page-tile home-page-tile__' + el
} else {
return 'home-page-tile'
}
}
}
}
}
</script>