Im using Nuxt.js, and have a custom component.
This component has css in the component that sets a background image using css.
I've tried the following but I get an error when I run this. The error is:
invalid expression: Invalid regular expression flags in
Component
<template>
<section class="bg-img hero is-mobile header-image" v-bind:style="{ backgroundImage: 'url(' + image + ')' }">
<div class="">
<div class="hero-body">
<div class="container">
<h1 class="title">
{{ result }}
</h1>
<h2 class="subtitle ">
Hero subtitle
</h2>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: ['result', 'image']
}
</script>
<style>
.bg-img {
background-image: url(~/assets/autumn-tree.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-color: #999;
}
</style>
I found the answer on https://github.com/nuxt/nuxt.js/issues/2123.
Basically, in the component do:
<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Content with background here</div>
url('~@/assets/autumn-tree.jpg')
I made the same mistake thinking this was a nuxtjs problem. Webpack uses syntax to resolve assets.
~ enforces webpack to treat the request as a module request. And then @ start at root.
<template>
<div>
<div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
</div>
</template>
<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
data() {
return { backgroundImagePath }
}
}
</script>
This is also another example using a combination of require and url to resolve an asset.
<b-col cols="8" class="hj_projectImage justify-content-center text-center" :style="{backgroundImage: `url(` + require(`~/assets/ProjectPictures/${this.ProjectPicture}`) + `)`}">
</b-col>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With