问题
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.
回答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>
来源:https://stackoverflow.com/questions/51643887/reference-assets-with-generated-style-data-bind