Dynamic CSS background images with Nuxt.js: a guide

Currently working with Nuxt.js and have developed a unique custom component.

The component contains CSS that applies a background image using styling.

However, the code I've implemented is resulting in an error message when attempting to run it. The specific error reads:

 invalid expression: Invalid regular expression flags in

Here is the Component Code:

<template>
  <section class="bg-img hero is-mobile header-image" v-bind:style="{ backgroundImage: 'url(' + image + ')' }">
    <div>
      <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>

Answer №1

I stumbled upon the solution at https://github.com/nuxt/nuxt.js/issues/2123.

Essentially, within the component, you can achieve this by:

<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Insert content with background here</div>

Answer №2

url('~@/assets/autumn-tree.jpg')

Initially, I incorrectly assumed that this was an issue with nuxtjs. In reality, webpack utilizes certain syntax to handle assets.

The tilde (~) signifies to webpack that the request should be treated as a module request, while the at symbol (@) indicates starting from the root directory.

Answer №3

This is a different example that showcases how to use both require and url together to locate an asset.

   <b-col cols="8" class="hj_projectImage justify-content-center text-center" :style="{backgroundImage: `url(` + require(`~/assets/ProjectPictures/${this.ProjectPicture}`) + `)`}">
  </b-col>

Answer №4

<template>
  <div>
    <div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
  </div>
</template>

<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
  data() {
    return { backgroundImagePath }
  }
}
</script>

Answer №5

One approach is to keep it simple by enclosing it in single quotes: 'background-image'

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

Answer №6

If you're looking for a great image solution, I highly recommend checking out nuxt-image

With nuxt-image, you have the ability to specify images based on resolution using media queries. Additionally, you can use the $img-feature to set images as background-images:

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

Answer №7

Having trouble with 'require' in my Nuxt3 project using Vite, resulting in a frustrating 500 error stating 'require not defined'.

To resolve this issue, I found a workaround by utilizing 'import' in the parent component and passing it down as a prop:

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>

Answer №8

If you're looking for a solution, the official documentation has it covered: https://nuxtjs.org/docs/2.x/directory-structure/assets#images

One simple step is all that's needed - just eliminate the slash:

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

For more dynamic imagery, such as ${image}.jpg:

<img :src="require(`~/assets/img/${image}.jpg`)" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Making an asynchronous call from Index.html to PHP Script

I am currently working on implementing an AJAX call to my PHP Script. While I can successfully echo the results from my data.php file, I am now facing a challenge regarding how to initiate the call from index.html in order to retrieve the table results s ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

Error Encountered in jQuery UI SelectMenu

Struggling to integrate the jQuery UI SelectMenu, I keep encountering the same error in the browser console. Below is the HTML Code: <select name="files" id="files"> <optgroup label="Scripts"> <option value="jquery">jQuery.js</ ...

Update the webpage post a database entry without relying on the setTimeout() function in Javascript

Is there a method to automatically refresh the page after a new entry in the database without relying on Javascript's setTimeout or setInterval functions? Could an AJAX function or a MySQL function accomplish this task instead? Must we continuously ...

What steps can I take to avoid unnecessary re-rendering of a variable that is not utilized in the HTML of my vue.js component?

I am currently in the process of replicating a real-life example of my code. In the actual code, this line represents a component that will continuously fetch an endpoint every few seconds, retrieving a random array of length "n", encapsulated wi ...

Switching Angular Buttons

I am developing an Angular application with a Bootstrap theme that includes 2 radio buttons, each triggering a separate page. It is important that only one radio button can be selected at a time. I want the class values to be btn btn-primary active for the ...

Steps to animate a div expanding to fit its content dimensions

I'm looking for a way to animate the opening of a div so that it adjusts to the size of its content. The content is fetched from a separate search using .load, which means it could be just a single line (no result) or multiple results that vary in hei ...

An issue occurred while trying to use the next() method with passport.authenticate('local') function

My current middleware setup involves the use of passport.js for user authentication before moving on to the next middleware: exports.authenticate = (req, res, next) => { passport.authenticate('local', (err, user, info) => { console.l ...

Live updating time and date functionality using JavaScript

Is it possible to dynamically display the time elapsed from now without refreshing the page? I'm considering using the date-fns package for this functionality. Can I use a Watcher in Vue JS to monitor changes in real-time? Any assistance on this matte ...

Uncertainties surrounding the complexity of this multi-stage form

Exploring this multi-step form I have a couple of questions: 1) Is there a way to transfer the value from the first step to the second step of the form? 2) How can I ensure that the datepicker value is not empty (to prevent user progress in the firs ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

Adjust: Return scale to default

By applying transform: rotate(-2deg); to a section, I have created an effect where the section rotates slightly. Additionally, when the user hovers over the same section, it increases in size due to transform: scale(1.1);. However, on one specific page of ...

Navigating through express.js async routing and managing errors

I am trying to streamline my route handling process by integrating error handling as middleware for my async function. Below is my current implementation: router.get( "/", asyncMiddleware( routeProviderMiddleware( async ({ y }) => ({ ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

AngularJS ng-view is a directive that views the application

I am currently struggling to create an angular js menu. I have been working on my code, but the pages are not loading as expected. Do you think I missed something or did I forget to include all the necessary scripts? I am fairly new to angular and could us ...

Struggling to choose an element with Selenium and Chrome?

I'm working on a script using Selenium and Chrome, but I'm facing issues with selecting and clicking on two specific elements. Let's take a look at the HTML code for these elements: HTML of Element 1: <td class="menuItem" id="tWlans" st ...