关于svg:vuecli中使用svgIcon

2次阅读

共计 1239 个字符,预计需要花费 4 分钟才能阅读完成。

一、装置依赖包

npm i -D svg-sprite-loader

二、配置 vue.config.js 文件

在 chainWebpack 中减少下列配置

chainWebpack (config) {config.module.rule('svg')
      .exclude.add(resolve('src/icons'))
    config.module.rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('./src/icons')).end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({symbolId: 'icon-[name]' })
  }

三、实现 SvgIcon 组件

组件构造如下:

<template>
  <svg :class="svgClass" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  computed: {iconName () {return `#icon-${this.iconClass}`
    },
    svgClass () {if (this.className) {return 'svg-icon' + this.className} else {return 'svg-icon'}
    }
  }
}
</script>

<style lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

四、根目录下创立 icons/svg 目录

用于寄存咱们所须要用的 svg 文件

五、新建 plugins 目录及 index.js 文件

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'

const req = require.context('@/icons/svg', true, /\.svg$/)
req.keys().map(req)

Vue.component('svg-icon', SvgIcon)

其作用是在 Vue 实例上创立 SvgIcon 组件,其中 require.context 的作用是获取一个特定的上下文, 遍历文件夹中的指定文件,次要用来实现自动化导入模块

  • 最初在 main.js 中引入 plugins, import '@/plugins'

六、SvgIcon 组件的应用

<svg-icon icon-class="icon-name" class="down"></svg-icon>

其中 icon-class 为 svg 文件名,class 为类名

正文完
 0