具有生成的样式数据绑定的参考资产 [英] reference assets with generated style data bind

查看:106
本文介绍了具有生成的样式数据绑定的参考资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用vue-cli 3,并希望生成背景图像路径.因此,我在v-for循环中使用样式数据绑定.

I'm using the vue-cli 3 and want to generate background-image paths. Therefore I'm using the style data bind within an 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

The images are in this folder: src/assets/icons/xxx.svg

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

The problem is, that the generated image path seems to be incorrect but I can't find the mistake.

推荐答案

这是因为webpack不会解析HTML内的任何路径(他还不是那么聪明-yet-).

That's because webpack is not parsing any path inside the HTML(he's not that smart -yet-).

无论如何,您可以欺骗webpack来获取您的URL.看起来真的不是我的最佳解决方案,但会回答您的问题.只需为包含所有工具及其图像路径的新列表创建一个计算属性.诀窍是让webpack解析该对象中的URL路径,然后在您的HTML中引用

Anyway, you could trick webpack to get the URL for you. 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

注意:我认为工具数组中的每个项目都是唯一的字符串.

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>

这篇关于具有生成的样式数据绑定的参考资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆