具有生成样式数据绑定的参考资产
reference assets with generated style data bind
我正在使用 vue-cli 3 并想要生成背景图像路径。因此,我在 v-for-loop 中使用样式数据绑定。
组件:
<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
中引用它
注意:我假设工具数组中的每一项都是一个唯一的字符串。
<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>
我正在使用 vue-cli 3 并想要生成背景图像路径。因此,我在 v-for-loop 中使用样式数据绑定。
组件:
<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
中引用它注意:我假设工具数组中的每一项都是一个唯一的字符串。
<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>