简体   繁体   中英

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>

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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