【问题标题】:Bind dynamic Vue image src from node_modules从 node_modules 绑定动态 Vue 图片 src
【发布时间】:2020-12-17 07:00:09
【问题描述】:

我正在创建一个 Vue 组件,它根据给定的图像名称或键(由 API 提供)显示来自我的节点模块的 SVG 图像。

如果我像~cryptocurrency-icons/svg/color/eur.svg一样直接放置源图像,则资源加载。

但如果我尝试使用 props 或使用 :src="imageSource" 分配它的安装方法来计算它,它不会加载。

我是 Vue 新手,所以我不知道为什么会这样?我应该使用下载到公共目录而不是 NPM 包中的图像吗?

<template lang="html">
<img src="~cryptocurrency-icons/svg/color/eur.svg"  alt="icon" />
</template>

<script lang="js">
export default {
    name: 'crypto-icon',
    props: ['currency'],
    mounted() {
        this.imageSource = `~cryptocurrency-icons/svg/color/${this.currency}.svg`
    },
    data() {
        return {
            imageSource: ""
        }
    },
    methods: {
        getImageResource(){
            return `~cryptocurrency-icons/svg/color/${this.currency}.svg`
        }
    },
    computed: {

    }
}
</script>

<style lang="scss" scoped>
.crypto-icon {}
</style>

【问题讨论】:

  • 试试this.imageSource = require(~cryptocurrency-icons/svg/color/${this.currency}.svg)

标签: node.js vue.js vuejs2 node-modules vue-loader


【解决方案1】:

您缺少require 属性。 Vue Loader 在编译单个文件组件中的 &lt;template&gt; 块时会自动执行此操作。试试这个:

require(`~cryptocurrency-icons/svg/color/${this.currency}.svg`)

您可以阅读更多here

【讨论】:

  • 使用require()时应去掉~符号。
【解决方案2】:

我已经通过使用 Vue 插件解决了这个问题(请参阅 vue-cryptoicons),虽然 hatef 关于使用 require 获取图像资源是正确的,但在 node_modules 下的目录中使用它会尝试找到完整路径

~cryptocurrency-icons/svg/color in ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"a7e19d86-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Wallet.vue?vue&type=template&id=7f1455a9&scoped=true&lang=html&

To install it, you can run: npm install --save ~cryptocurrency-icons/svg/color

【讨论】:

  • 嗯,应该也可以在node directory 下工作。也许它被缓存了?但是,无论如何,从node_modules 目录中读取媒体并不是一个好主意,因为您最终可能会更新软件包并且您的媒体已经消失了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多