Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 305
FAYA Avatar asked Oct 14 '25 15:10

FAYA


1 Answers

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.

like image 125
hatef Avatar answered Oct 17 '25 09:10

hatef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!