14

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>

8 Answers 8

17

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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.
12

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.

Comments

7

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>

Comments

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>

1 Comment

adding a verbal explanation is often helpful
1

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

v-bind:style="{ 'background-image': 'url(' + api.url + ')' }"

Comments

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}')`
      }
    }
  }
}

1 Comment

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?
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>

Comments

-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`)" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.