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
JavaScript
x
2
1
<img :src="require(`@/assets/images/${backgroundImage}`)" />
2
But obviously this needs to be an inline background image.
Code:
component
JavaScript
1
36
36
1
<template>
2
<div
3
class="w-full h-64 bg-auto bg-no-repeat bg-center lg:bg-cover relative"
4
:style="{ backgroundImage: url(require('@/assets/images/' + backgroundImage))}"
5
>
6
<div class="w-full h-full flex flex-col justify-center items-center text-white px-6">
7
<div class="hero-text rounded text-center py-8 px-12">
8
<p class="text-base lg:text-md uppercase font-medium">{{ smallLeadingText }}</p>
9
<h1 class="text-xl md:text-3xl lg:text-5xl uppercase font-bold">{{ mainText }}</h1>
10
<p class="text-base lg:text-md">{{ subText }}</p>
11
</div>
12
</div>
13
</div>
14
</template>
15
16
<script>
17
export default {
18
name: "PageHero",
19
props: {
20
backgroundImage: String,
21
smallLeadingText: {
22
type: String,
23
required: false
24
},
25
mainText: {
26
type: String,
27
required: true
28
},
29
subText: {
30
type: String,
31
required: false
32
}
33
}
34
};
35
</script>
36
View
JavaScript
1
7
1
<PageHero
2
backgroundImage="mc-background.png "
3
smallLeadingText="Powerful, secure & affordable"
4
mainText="Minecraft hosting"
5
subText="Plans suitable for all budgets"
6
/>
7
Advertisement
Answer
Looks like you’ve just got some syntax errors in your style
attribute around string quoting. Try
JavaScript
1
2
1
<div :style="{ backgroundImage: `url(${require('@/assets/images/' + backgroundImage)})` }">
2
Might be easier to create some computed properties to resolve everything though
JavaScript
1
11
11
1
computed: {
2
bgImage () {
3
return require('@/assets/images/' + this.backgroundImage)
4
},
5
inlineStyle () {
6
return {
7
backgroundImage: `url(${this.bgImage})`
8
}
9
}
10
}
11
and
JavaScript
1
2
1
<div :style="inlineStyle">
2