nuxt.js - how to set css background image dynamicaly
Asked Answered
E

8

13

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>
Erg answered 25/1, 2018 at 5:7 Comment(0)
E
16

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>
Erg answered 25/1, 2018 at 6:11 Comment(1)
Just to note, this isn't specific to Nuxt, rather it's just a Vue template convention for binding a data value to the style attribute on an HTML element.Thorner
R
11

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.

Ruyle answered 9/4, 2020 at 19:47 Comment(0)
C
6

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>
Consonance answered 13/12, 2020 at 10:47 Comment(0)
V
5
<template>
  <div>
    <div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
  </div>
</template>

<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
  data() {
    return { backgroundImagePath }
  }
}
</script>
Volteface answered 31/8, 2020 at 12:41 Comment(1)
adding a verbal explanation is often helpfulHusein
D
1

You can write it normally but in '': 'background-image'

v-bind:style="{ 'background-image': 'url(' + api.url + ')' }"
Debarath answered 26/1, 2018 at 3:53 Comment(0)
D
1

Overall I recommend using nuxt-image

There you can define the images per resolution (media-query). Using the $img-feature you can also define it as background-image:

export default {
  computed: {
    backgroundStyles() {
      const imgUrl = this.$img('https://github.com/nuxt.png', { width: 100 })
      return {
        backgroundImage: `url('${imgUrl}')`
      }
    }
  }
}

Dicast answered 20/2, 2022 at 13:19 Comment(1)
I'm using nuxt image at the moment, Is using the $img, the recommended way to get background images to work while keeping the sizing properties?Antimatter
S
0

So, require doesn't work in my Nuxt3 w/ Vite app and I get the nasty 500 error with 'require not defined'.

This is my solution using import in the parent page and passing it via props:

Parent Component:

<template>
  <div class="flex flex-col h-screen">
    <NavHeader />
    <HeroPage
      :pageImage="pageImage"
    />
    <NavFooter />
  </div>
</template>

<script>
//Import the banner image.
import pageImage from "~/assets/banner/page-banner-about-us.jpg";

export default {
  data() {
    return {
      pageImage: pageImage
    };
  },
};
</script>

Child Component:

<template>
  <div
    class="mx-auto relative block w-[1200px] top-0 z-10 overflow-hidden mt-0 mb-0 bg-cover py-16 rounded-b-lg"
    :style="bgImage"
  >
  </div>
</template>

<script>
export default {
  props: {
    pageImage: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      bgImage: {
        "background-size": "cover",
        "background-image": `url(${this.pageImage})`,
      },
    };
  },
};
</script>
Sucre answered 2/8, 2023 at 15:34 Comment(0)
B
-1

The official documentation provides the solution already, see: https://nuxtjs.org/docs/2.x/directory-structure/assets#images

All you need to do is to remove the slash:

background-image: url("~assets/autumn-tree.jpg");

For really dynamic image e.g. ${image}.jpg:

<img :src="require(`~/assets/img/${image}.jpg`)" />
Bowlder answered 3/3, 2021 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.