【问题标题】:reference assets with generated style data bind具有生成的样式数据绑定的参考资产
【发布时间】:2019-01-09 15:37:12
【问题描述】:

我正在使用 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

问题是,生成的图像路径似乎不正确,但我找不到错误。

【问题讨论】:

    标签: css webpack vue.js assets


    【解决方案1】:

    那是因为 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>
    

    【讨论】:

    • 感谢您的帮助!但是有一个问题:运行此代码会在终端中给我一条错误消息,没有任何进一步的解释。它只是说“ERROR Failed to compile with 1 errors”。我的 IDE 中也没有显示错误。我只在我的工具数组中使用唯一的字符串。有什么想法吗?
    • ok 已根据我的需要修复了它——计算属性中的 require 路径不适合我的结构。这里是工作路径:img: require(@/assets/icons/${tool}.svg)
    • 我给你的代码更像是一个提示,所以你可以找出使它适合你的需要的方法,并且由于你没有提供关于你正在使用的数据类型的更多信息,它肯定会引发一些错误。不过我很高兴它有所帮助。
    猜你喜欢
    • 2022-07-05
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多