简体   繁体   English

具有生成的样式数据绑定的参考资产

[英]reference assets with generated style data bind

I'm using the vue-cli 3 and want to generate background-image paths. 我正在使用vue-cli 3,并希望生成背景图像路径。 Therefore I'm using the style data bind within an v-for-loop. 因此,我在v-for循环中使用样式数据绑定。

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 图像位于此文件夹中:src / assets / icons / xxx.svg

The problem is, that the generated image path seems to be incorrect but I can't find the mistake. 问题是,生成的图像路径似乎不正确,但是我找不到错误。

That's because webpack is not parsing any path inside the HTML(he's not that smart -yet-). 那是因为webpack不会解析HTML内的任何路径(他还不那么聪明-yet-)。

Anyway, you could trick webpack to get the URL for you. 无论如何,您都可以欺骗webpack为您获取URL。 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 诀窍是让webpack解析该对象中的URL路径,然后在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM