Carlos Pisarello
Carlos Pisarello

Reputation: 1284

Pass assets image path as dynamic inline style background-image url (Nuxt.js)

I'm working on a Nuxt.js app and I want to set the background image of an element dynamically with images from the assets folder, this is what I did:

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

The div is rendered with dynamic background images

Actual behavior

The background image is not rendered. If I put the static assets path into css file, it is rendered

How do I have to pass the path for this to be rendered correctly?

Upvotes: 2

Views: 4323

Answers (1)

Bryce Howitson
Bryce Howitson

Reputation: 7690

Nuxt Webpack build process messes with some urls

So the issue is that paths in templates and CSS are processed by Webpack's file-loader when the project is built. For example ~assets/ gets rewritten at build time to be the actual path after webpack's processing is done.

However, since you're specifying the path strings as part of the vue.js data, Webpack doesn't touch them.

To resolve this create a "static" directory at the root of your project (assuming you don't have one already). Inside of that, create an "images" directory. Webpack will copy everything thing inside static to the dist folder when the build is run.

The path to these images to use inside your component is then /images/filename.ext

Upvotes: 6

Related Questions