【问题标题】:images is not found when passing image name to vue component将图像名称传递给vue组件时找不到图像
【发布时间】:2020-07-30 08:54:37
【问题描述】:

我正在尝试动态创建输入组件,因为我需要为每个输入指定一个特定的图标。 图标设置为输入作为背景图像,当我直接在 css 中使用它时它可以工作,就像background-image: url(../../assets/icons/email.svg);

但是当我传递组件的图标名称时,应用程序说找不到!

    <template>
        <section class="input-box">
            <input class="input-field" type="text" :style="imgIcon">
            <label>{{title}}</label>
        </section>
    </template>

    <script>
      export default {
        props: ["title", "bgImg"],
        computed: {
          imgIcon() {
            return 'background-image: url(./assets/icons/' + this.bgImg + ')';
          }
        }
      }
    </script>

当我将名称作为字符串传递时

<custome-input title="password" bgImg="'p_key.svg'"></custome-input>

错误已解决,但没有任何显示!

到底出了什么问题?

【问题讨论】:

  • 你不应该在 vue 中使用相对路径。尝试改用 @ 别名。它是根目录的别名。
  • @Nicolas 我试过这个return 'background-image: url(@/assets/icons/' + this.bgImg + '.svg)';,但也没有用
  • 我认为网址也需要用引号引起来。 :return 'background-image: url(\'@/assets/icons/' + this.bgImg + '.svg\')'
  • 也没有用。仍然说找不到该文件:/

标签: javascript html css vue.js vue-component


【解决方案1】:

绑定动态图片时使用require

computed: {
  imgIcon() {
    try {
      return 'background-image: url(' + require('@/assets/icons/' + this.bgImg) + ')';
    } catch(error) {
      return ''; 
    }
  }
}

您在 cmets 中提到的错误是因为路径的一部分是第一次计算时可能尚未定义的道具,因此将其包装在 try 块中。

【讨论】:

  • 这成功了!但是当使用@ 时会出错,所以我需要使用点来定位文件夹。是什么导致了这个问题?
  • 这个错误Can't resolve '@/assets/icons'。此路径等于../../assets/icons
  • 好吧,我更新了答案。 @src 目录的别名
  • 还有一个问题。当我尝试使用组件而不传递图像名称时。整个组件消失了,我收到此错误 Error in render: "Error: Cannot find module './' 。有时我可能不需要使用背景图片。除了改变组件的其他用途的样式,还有什么解决办法吗?
  • 好的。您对答案的最后编辑也适用于我的问题。谢谢你的帮助^^
【解决方案2】:

如果你想使用模板中的图片,你需要使用@并且url应该是一个字符串。

export default {
  props: ["title", "bgImg"],
  computed: {
    imgIcon() {
      return `background-image: url('@/assets/icons/${this.bgImg}')`;
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2018-11-12
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多