如何通过vue-svg-loader在vue.js中导入多个svg [英] How to import multiple svgs in vue.js via vue-svg-loader

查看:47
本文介绍了如何通过vue-svg-loader在vue.js中导入多个svg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个vue组件中导入多个svg.文档说我必须导入每个svg,但是如何以更短,更简洁的方式导入多个svg?

I want to import multiple svg's in one vue component. The documentation says I Have to import each one of them, but how can I import multiple svgs in a much shorter and cleaner way?

vue-svg-loader文档: https://vue-svg-loader.js.org/

vue-svg-loader documentation: https://vue-svg-loader.js.org/

<script>
import Info from "@/assets/svgs/info.svg";
import Help from "@/assets/svgs/help.svg";
import Close from "@/assets/svgs/close.svg";
// etc. pp.

export default {
  components: {
    Info,
    Help,
    Close
  }
</script>

如果要导入的svg超过100,会发生什么?

What happens if I got over one hundred svg's I want to import?

有什么办法解决这个问题吗?

Any ideas to solve this?

推荐答案

创建基础组件,并在全局进行注册,因为您会经常使用它.

Create a base component and register it globally since you'll use it very frequently.

创建一个< BaseIcon> 组件,该组件使用

Create a <BaseIcon> component that uses require with expression to create a context for the SVG modules:

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

<script>
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 */
 }
 </style>

注意:我们使用< Component> 处理动态组件,它假定您将使用 vue-svg-loader 并且SVG被视为组件.如果不是这种情况,请使用< img> 标记,并使用 src 代替 is .

Note: We use <Component> to handle dynamic components, which assumes you'll use vue-svg-loader and the SVGs are treated as components. If that is not the case, use an <img> tag instead and use src instead of is.

全局注册基本组件:

如果仅创建一个基本组件,则只需转到 main.js 文件,然后在安装应用程序之前执行以下操作:

If you're only creating a single base component, you can just go to your main.js file and before mounting the app do:

import Vue from 'vue'
import BaseIcon from './components/_base/BaseIcon.vue'
import App from './App.vue'

Vue.component('BaseIcon', BaseIcon)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

否则,如果您需要更复杂的内容,请看看

Else, if you want something a little bit more complex, take a look at how this boilerplate registers base components automatically.

最后,像这样使用组件:

Finally, use the component like so:

<template>
  <div>
    <BaseIcon
      name="info"
    />
    <BaseIcon
      name="help"
    />
    <BaseIcon
      name="close"
    />
  </div>
</template>

<script>
export default {
  name: 'SomeComp',
}
</script>

这篇关于如何通过vue-svg-loader在vue.js中导入多个svg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆