Bind dynamic Vue image src from node_modules

1.2k Views Asked by At

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).

If I put the source image directly like ~cryptocurrency-icons/svg/color/eur.svg, the resource loads.

But if I try to compute it with the props or by the mounted method asigning it using :src="imageSource" it does not load.

I'm new to Vue so I don't know why is this happening? Should I use images downloaded in a public directory instead of the NPM package?

<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>
2

There are 2 best solutions below

1
On

You are missing the require attribute. Vue Loader, does this automatically when it compiles the <template> blocks in single file components. Try with this:

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

You can read more here.

1
On

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

~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