Utilize dynamic inline styling to pass asset image paths as background images in Nuxt.js

I am in the process of developing a Nuxt.js application and I have a requirement to dynamically set the background image of an element using images from the assets folder. Here is what I have implemented:

<template>
  <div>
    <div
      v-for="(image, imageID) in images"
      :key="imageID"
      :style="bgImg(image)"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      images: [
        '~assets/img/image1.jpg',
        '~assets/img/image2.jpg',
        '~assets/img/image3.jpg',
        '~assets/img/image4.jpg'
      ]
    }
  },
  methods: {
    bgImg(img) {
      return `background-image: url(${img})`
    }
  }
}
</script>

Expected outcome

The div should be displayed with dynamic background images.

Current outcome

The background image is not being displayed. However, if I use the static asset path in the CSS file, it works fine.

What is the correct way to pass the path for the background image to display correctly?

Answer №1

Nuxt Webpack build process causes issues with certain URLs

One of the challenges you may encounter is that paths in templates and CSS are altered by Webpack's file-loader during the project's compilation. For instance, ~assets/ is transformed at build time to the actual path after undergoing Webpack's processing.

However, when the path strings are specified as part of the data in vue.js, Webpack does not modify them.

To tackle this problem, establish a "static" folder at the root of your project (if one doesn't already exist). Within this folder, create an "images" directory. When the project is built, Webpack will duplicate everything inside the static folder to the dist folder.

The appropriate image path to utilize within your component is then /images/filename.ext

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

Obtain the content slot in Vue.js 2 and convert it into a string

Is it possible to retrieve the string inside a slot before that slot is compiled? For example: <div> <slot> <component-test text="test1"></component-test> </slot> </div> I am looking for the result "<co ...

The -webkit-linear-gradient effect can lead to noticeable banding issues on Chrome and Safari browsers

The title pretty much sums it up. The first image below is a screenshot of a page that is about 8000 pixels tall, taken in the most recent version of Chrome: On the other hand, this image depicts a different page (with the same CSS), which is only about 8 ...

Issue in Vuetify: The value of the first keypress event is consistently an empty string

I need to restrict the user from entering numbers greater than 100. The code snippet below represents a simplified version of my production code. However, I am facing an issue where the first keypress always shows an empty string result. For example, if ...

Unable to locate any static exports within the TypeScript library bundle

In my file Style.ts, I have a class called Style: export class Style { ... } The Style class consists of properties, methods, and a constructor, along with import statements for other class dependencies. It is being used by other classes through the ...

Enhance your SVG progress circle by simply selecting checkboxes

I have a unique system with 5 checkboxes that act as a To-Do list. When I click on each checkbox, the circle's diameter should progressively fill up in increments of 1/5 until all 5 checkboxes are completed. The order in which the checkboxes are click ...

What could be causing the lack of downward rotation of my arrow in css? (specifically, the span element)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=de ...

Guide on adding a parent class to style all generated CSS rules in styled-components 5.3.5

When my application loads into a parent div with a specific class (for example, .my-app), is there a way to add the prefix .my-app to all classes generated by styled-components? For instance, consider a component like this: import React from 'react& ...

VueJS advisory: Refrain from directly altering a prop

When attempting to modify a prop value using the @click directive, I encountered a warning message: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed pr ...

How can CSS Bootstrap flex width be used to prevent parent element from expanding too much with long, single line text? Utilizing ell

​Having encountered a tricky situation with CSS and flexbox, I found myself needing to implement the following properties: ​text-overflow: ellipsis; ​white-space: nowrap; ​overflow: hidden; However, when the text was too long, it caused t ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Position the div in the center of a container that is 100% width and has floating elements with dynamic widths

I am looking to align 3 divs inside a container div, with the arrangement of [LEFT] [CENTER] [RIGHT]. The container div should be 100% wide without a fixed width, and I want the center div to stay centered even when resizing the container. The left and ...

What are the best strategies for addressing cache issues in today's web browsers?

We are currently working on a VueJS-based application and facing a significant caching issue. Despite team members continuously updating the site, we keep receiving feedback about already resolved problems such as typos and misplaced elements. In my atte ...

Tips for reintroducing a previously deleted shape into the canvas using Konva

I recently removed a rectangle from the scene using the remove() method. Now, I am trying to figure out how to draw it back. According to the documentation: "remove a node from parent, but don't destroy. You can reuse the node later." Here is the li ...

The default export (imported as 'Vue') could not be located within the 'vue' module in Vue 3 and Laravel

I'm currently in the process of building a project that combines Laravel 8 and Vue JS 3. I've set everything up, but whenever I try running `npm run watch`, I encounter an error message similar to the one below. Despite looking through various fo ...

Unusual Behavior of CSS and JQuery Selectors

As I was working with jquery selectors, I encountered something quite unexpected. This is an example of my HTML: <ul id="unordered-list"> <li> <img src="https://www.google.com/images/srpr/logo4w.png" width="40" height="40"/> ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

What are some methods for applying border styles to the first and last row of a table using Material UI?

In my current project, I am utilizing the combination of Material UI and React Table. Recently, I was asked to implement an expandable row feature, which I successfully added. Once the user expands the row, we need to display additional table rows based on ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

JS glitch leading to oversized window dimensions - Issue with dropdown menu

I recently integrated a dropdown into my website using Foundation CSS. To see the dropdown in action, you can login with the credentials provided (username: stackoverflow password: testtest) on . However, I noticed that when logged in, the page on the rig ...

Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values? Is there a way to iterate only over the keys? export enum Colors { "RED" = 1, "BLUE" = 2, "GREEN" = 3, } <template> <div> <v ...