繁体   English   中英

从 node_modules 绑定动态 Vue 图像 src

[英]Bind dynamic Vue image src from node_modules

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

如果我像~cryptocurrency-icons/svg/color/eur.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>

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

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

您可以在此处阅读更多内容。

我已经通过使用 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