美文网首页vue学习
Vue中使用SVG封装成SVG组件

Vue中使用SVG封装成SVG组件

作者: O槑頭槑腦 | 来源:发表于2019-03-06 10:53 被阅读0次

一、在vue脚手架生成的文件夹下的src/components创建一个Svg

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

<script type="text/ecmascript-6">
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>
.svg-icon {
      width: 1em;
      height: 1em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
  }
</style>

二、使用和安装svg-sprite

  • 这里使用webpack loader中的一个svg-sprite-loader,可以将多个svg打包成svg-spite

1、安装

npm install svg-sprire-loader --save-dev

2、配置 build/webpack.base.conf.js

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

四、自动导入

  • 自动导入需要用到webpack的require context
// require.context的简单介绍
require.context("./file", false, /.file.js$/);
这行代码就会去 file 文件夹(不包含子目录)下面的找所有文件名以 .file.js 结尾的文件能被 require 的文件。就是说可以通过正则匹配引入相应的文件模块。

// require.context有三个参数:
directory:说明需要检索的目录
useSubdirectories:是否检索子目录
regExp: 匹配文件的正则表达式
  • 在src/icons/index.js使用require context
import Vue from 'vue'
import SvgIcon from '../components/SvgIcon.vue'

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

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

五、在main.js中引入

import '@/icons'

六、在src/icons/svg下面的各个文件

相关文章

网友评论

    本文标题:Vue中使用SVG封装成SVG组件

    本文链接:https://www.haomeiwen.com/subject/qkftpqtx.html