简体   繁体   English

从 node_modules 绑定动态 Vue 图像 src

[英]Bind dynamic Vue image src from node_modules

I' am creating a Vue component that shows an SVG image from my node modules based on a given image name or key (given by an API).我正在创建一个 Vue 组件,该组件根据给定的图像名称或键(由 API 提供)显示来自我的节点模块的 SVG 图像。

If I put the source image directly like ~cryptocurrency-icons/svg/color/eur.svg , the resource loads.如果我像~cryptocurrency-icons/svg/color/eur.svg一样直接放置源图像, ~cryptocurrency-icons/svg/color/eur.svg加载资源。

But if I try to compute it with the props or by the mounted method asigning it using :src="imageSource" it does not load.但是,如果我尝试使用 props 或通过使用:src="imageSource"分配它的挂载方法来计算它,它不会加载。

I'm new to Vue so I don't know why is this happening?我是 Vue 的新手,所以我不知道为什么会这样? Should I use images downloaded in a public directory instead of the NPM package?我应该使用在公共目录中下载的图像而不是 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>

You are missing the require attribute.您缺少require属性。 Vue Loader, does this automatically when it compiles the <template> blocks in single file components. Vue Loader 在编译单个文件组件中的<template>块时会自动执行此操作。 Try with this:试试这个:

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

You can read more here .您可以在此处阅读更多内容。

I've solved it by using a Vue plugin (see vue-cryptoicons ), although hatef is right about using require for image resources, using it in directories under node_modules tries to find the full path我已经通过使用 Vue 插件解决了它(请参阅vue-cryptoicons ),尽管 hatef 对图像资源使用require是正确的,但在node_modules下的目录中使用它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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM