0

I'm using the vue-cli 3 and want to generate background-image paths. Therefore I'm using the style data bind within an v-for-loop.

the component:

<template>
    <ul>
      <li v-for="(tool, index) in tools" :key="index">
        <a href="#" :style="{ backgroundImage: 'url(@/assets/icons/' + tool + '.svg)' }"></a>
      </li>
    </ul>
</template>

<script>
export default {
  props: {
    tools: Array,
  }
}
</script>

The images are in this folder: src/assets/icons/xxx.svg

The problem is, that the generated image path seems to be incorrect but I can't find the mistake.

Frondor
  • 3,466
  • 33
  • 45
iamrobin.
  • 1,554
  • 3
  • 19
  • 31

1 Answers1

1

That's because webpack is not parsing any path inside the HTML(he's not that smart -yet-).

Anyway, you could trick webpack to get the URL for you. Doesn't look really like the best solution to me, but will answer your question. Just create a computed property for a new list containing all the tools with their image paths. The trick is letting webpack parse the URL path for you in that object, then reference it in your HTML

Note: I supposed each item in the tools array is an unique string.

<template>
    <ul>
      <li v-for="tool in items" :key="tool.name">
        <a href="#" :style="{ backgroundImage: `url(${tool.img})` }"></a>
      </li>
    </ul>
</template>

<script>
export default {
  props: {
    tools: Array,
  },
  computed: {
    items () {
      return this.tools.map(tool => {
        return {
          name: tool,
          // the trick is letting webpack parse the URL path for you
          img: require(`@/assets/icons/${tool}.svg`)
        }
      })
    }
  }
}
</script>
Frondor
  • 3,466
  • 33
  • 45
  • Thanks for your help! But there is one problem: running this code gives me an error message in the terminal, without any further explanation. It just says "ERROR Failed to compile with 1 errors ". Also there is no error shown in my IDE. I only use unique strings in my tools array. Any idea? – iamrobin. Aug 02 '18 at 09:24
  • ok fixed it for my needs – the require path inside the computed property doesn't fit my structure. Here is the working path: img: require(`@/assets/icons/${tool}.svg`) – iamrobin. Aug 02 '18 at 09:50
  • 1
    The code I gave you was more like a hint so you could figure out the way to make it fit your needs, and since you didn't provide more information about the data types you were working with, it was going to throw some error for sure. I'm glad it helped though. – Frondor Aug 03 '18 at 01:15