Vue引入本地SVG文件

目录结构(需要修改/新增的文件)

build\
    webpack.base.conf.js
src\
    components\
        SvgIcon\
            index.vue
    icons\
        svg\
            *.svg
        index.js
    main.js

src目录下创建icons文件夹,里面创建svg文件夹和index.js文件,svg文件夹中存放扩展的.svg图标文件

创建SvgIcon组件,/src/components/SvgIcon/index.vue

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

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

<style scoped>
.svg-icon {
  width: 1.2em;
  height: 1.2em;
  vertical-align: -0.18em;
  fill: currentColor;
  overflow: hidden;
}
</style>

引入所有扩展的SVG图标文件,/src/icons/index.js

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件

// register globally
Vue.component('svg-icon', SvgIcon)

const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

main.js中引入icons,/src/main.js

import './icons'

下载svg-sprite-loader插件

cnpm i svg-sprite-loader --save

build配置,build/webpack.base.conf.js

加入

{
      test: /\.svg$/,
      loader: 'svg-sprite-loader',
      include: [resolve('src/icons')],
      options: {
          symbolId: 'icon-[name]'
      }
}

并在以下设置中添加exclude: [resolve('src/icons')],

{
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    exclude: [resolve('src/icons')],
    options: {
        limit: 10000,
        name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
},

使用

把<svg>的icon-class属性设置为.svg文件的名称来引用

<svg-icon icon-class="user"/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 阿里巴巴的iconfont是一个很好的图标库,海量的素材可以快速满足开发人员日常对图标的诉求,我们采用symbol...
    知足常乐晨阅读 29,513评论 3 20
  • 在上一章完成登录页面基本结构之后,svg虽然也写进去了,可怎么都不显示,这章就是解决这个问题。 在vue项目中使用...
    Memory_2e2e阅读 3,575评论 0 0
  • 1、创建SvgIcon组件,在vue项目的components/SvgIcon目录下创建index.vue文件,代...
    zccoften阅读 472评论 0 0
  • 前言 更多内容,请访问我的 个人博客。 创建SvgIcon组件 在 components 文件夹下新建 SvgIc...
    潘高PG阅读 8,050评论 2 3
  • 一夜知秋 路边到处散落着柳树叶儿 卷卷的,黄黄的 夏天就这么过去了吗 我还没听得 几下蛙叫 几声蝉鸣 也还没能来得...
    太白飞歌阅读 262评论 0 0