css - 具有生成样式数据绑定(bind)的引用 Assets

标签 css webpack vue.js assets

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

相关文章:

vue.js - 生产和暂存构建不同

html - CSS - Dropbox 网站页脚效果?

html - 为什么内容 float 在 DIV 旁边?

vue.js - Storybook 6.x 和 Vue 2 在需要额外加载器时失败

reactjs - 不支持的 vendor 前缀样式属性 webkitAppearance。您指的是 WebkitAppearance 吗?

vue.js - 删除 Nuxt/Vue 中的事件监听器

html - Accordion 内元素的弹出窗口(Bootstrap)

javascript - 创建 Canvas 矩阵

ruby-on-rails - 使用 webpack 部署到 Heroku 时预编译 Assets 时出错

vue.js - Vue 在 init 之后动态创建 computed