【问题标题】:How can I dynamically load svg icons from node_modules folder in my nuxt js component?如何从我的 nuxt js 组件中的 node_modules 文件夹动态加载 svg 图标?
【发布时间】:2021-10-10 16:58:41
【问题描述】:

我正在尝试在我的 Nuxt SSR 项目中使用来自 Github 的这个库 cryptocurrency-icons

此库将所有 svg 图标添加到 ./node_modules/cryptocurrency-icons/svg/color 目录

我在 components/BaseCryptoIcon.vue 文件中做了如下组件

<template>
  <Component
    :is="
      require(`~/node_modules/cryptocurrency-icons/svg/color/${name}.svg`)
        .default
    "
    class="BaseIcon"
    v-bind="$attrs"
    @v-on="$listeners"
  />
</template>

<script>
/**
 * https://stackoverflow.com/questions/59148672/how-to-import-multiple-svgs-in-vue-js-via-vue-svg-loader
 */
export default {
  name: 'BaseIcon',

  // Transparent wrapper component
  // https://vuejs.org/v2/guide/components-props.html#Disabling-Attribute-Inheritance
  inheritAttrs: false,

  props: {
    name: {
      type: String,
      required: true,
    },
  },
}
</script>

<style>
.BaseIcon {
  /* Add some default CSS declaration blocks */
  width: 32px;
  height: 32px;
}
</style>

当我尝试在我的 pages/Index.vue 文件中使用它时,没有呈现任何内容。它也没有给出任何错误

<template lang="pug">
  base-crypto-icon(name='btc')
</template>

<script lang="javascript">
import BaseCryptoIcon from '~/components/BaseCryptoIcon.vue'
export default {
  components: {BaseCryptoIcon}
}
</script>

谁能告诉我如何在 Vue/Nuxt 中完成这项工作

【问题讨论】:

  • 您是否在(浏览器和服务器)双方都检查错误?什么是行为?组件没有被渲染或以某种方式损坏?

标签: vue.js svg vuejs2 vue-component nuxt.js


【解决方案1】:

你可以尝试在 components/BaseCryptoIcon.vue 中制作方法:

getIcon(name)  {
  return require(`~/node_modules/cryptocurrency-icons/svg/color/${name}.svg`).default
}

然后在模板中:

 <Component
    :is="getIcon(name)"
  />

2天前可能相关的问题: Why image path is not resolved by require() when passed as prop in NuxtJS?

【讨论】:

  • :( 运气不好它不会渲染
  • 你的问题很可能是需要的。特别是如果您在道具内制作 require().default 。将脚本区域中的所有复杂操作留在模板之外是一种很好的做法。
  • 这很完美,只需将@nuxtjs/svg 模块添加到nuxt 配置文件!谢谢你安德烈,你拯救了我的一天
  • 耶! (我的意思是 Yarrr!)我很高兴能帮助你的生活,海盗人! :)
猜你喜欢
  • 2019-05-03
  • 2020-10-08
  • 2019-09-17
  • 2021-10-17
  • 2022-07-19
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多