Vue动态背景图片内联组件 [英] Vue dynamic background image inline component
问题描述
我正在用 Vue 构建一个需要动态背景的横幅,但是,它似乎不起作用.不知道我做错了什么.我已经尝试了其他一些方法,如果我做一个像
这样的图像标签,它会起作用<img :src="require(`@/assets/images/${backgroundImage}`)"/>
但显然这需要是一个内嵌的背景图片.
代码:
组件
</模板><脚本>导出默认{name: "PageHero",道具: {背景图片:字符串,小标题文本:{类型:字符串,要求:假},正文:{类型:字符串,要求:真实},子文本:{类型:字符串,要求:假}}};
查看
看起来您的 style
属性中出现了一些有关字符串引用的语法错误.试试
<div :style="{ backgroundImage: `url(${require('@/assets/images/' + backgroundImage)})` }">
<小时>
创建一些计算属性来解决所有问题可能更容易
计算:{背景图像(){return require('@/assets/images/' + this.backgroundImage)},内联样式(){返回 {背景图片:`url(${this.bgImage})`}}}
和
演示 ~ https://codesandbox.io/s/crimson-sky-ehn9r
I'm building a banner with Vue that needs to have a dynamic background, however, it doesn't seem to be working. Not sure what I'm doing wrong. I've tried a few other ways and it works if I do an image tag something like
<img :src="require(`@/assets/images/${backgroundImage}`)" />
But obviously this needs to be an inline background image.
Code:
component
<template>
<div
class="w-full h-64 bg-auto bg-no-repeat bg-center lg:bg-cover relative"
:style="{ backgroundImage: url(require('@/assets/images/' + backgroundImage))}"
>
<div class="w-full h-full flex flex-col justify-center items-center text-white px-6">
<div class="hero-text rounded text-center py-8 px-12">
<p class="text-base lg:text-md uppercase font-medium">{{ smallLeadingText }}</p>
<h1 class="text-xl md:text-3xl lg:text-5xl uppercase font-bold">{{ mainText }}</h1>
<p class="text-base lg:text-md">{{ subText }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: "PageHero",
props: {
backgroundImage: String,
smallLeadingText: {
type: String,
required: false
},
mainText: {
type: String,
required: true
},
subText: {
type: String,
required: false
}
}
};
</script>
View
<PageHero
backgroundImage="mc-background.png "
smallLeadingText="Powerful, secure & affordable"
mainText="Minecraft hosting"
subText="Plans suitable for all budgets"
/>
解决方案 Looks like you've just got some syntax errors in your style
attribute around string quoting. Try
<div :style="{ backgroundImage: `url(${require('@/assets/images/' + backgroundImage)})` }">
Might be easier to create some computed properties to resolve everything though
computed: {
bgImage () {
return require('@/assets/images/' + this.backgroundImage)
},
inlineStyle () {
return {
backgroundImage: `url(${this.bgImage})`
}
}
}
and
<div :style="inlineStyle">
Demo ~ https://codesandbox.io/s/crimson-sky-ehn9r
这篇关于Vue动态背景图片内联组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文