我正在使用 vue-cli 3 并想要生成背景图像路径。因此,我在 v-for-loop 中使用样式数据绑定(bind)。
组件:
<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>
图片在这个文件夹中:src/assets/icons/xxx.svg
问题是,生成的图像路径似乎不正确,但我找不到错误。
最佳答案
那是因为 webpack 没有解析 HTML 中的任何路径(他还没有那么聪明)。
无论如何,您可以欺骗 webpack 为您获取 URL。对我来说看起来不是最好的解决方案,但会回答您的问题。 只需为包含所有工具及其图像路径的新列表创建一个计算属性。诀窍是让 webpack 在该对象中为您解析 URL 路径,然后在您的 HTML 中引用它
注意:我假设 tools 数组中的每一项都是一个唯一的字符串。
<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>
关于css - 具有生成样式数据绑定(bind)的引用 Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643887/