svg组件封装

npm install svg-sprite-loader -S

vue2

src/components/SvgIcon/index.vue

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

<script>
export default {
  name: "SvgIcon",
  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 scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

src/icons/index.js

import Vue from 'vue'
// 导入显示、渲染 SVG 组件
import SvgIcon from '@/components/SvgIcon'// svg component

// 将 SvgIcon 组件注册为全局组件
Vue.component('svg-icon', SvgIcon)

// 使用 webpack 提供的方法,查找 svg 目录下所有的 .svg 文件
const req = require.context('./svg', false, /\.svg$/)
// 将每一个 svg 文件转换成相关的属性,然后交给 SvgIcon 进行使用
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

src/main.js

import '@/icons' // 引入字体图标

vue.config.js

const path = require('path')
module.exports = {
    chainWebpack: config => {
        const svgRule = config.module.rule('svg')
        svgRule.uses.clear()
        svgRule
            .test(/\.svg$/)
            .include.add(path.resolve(__dirname, './src/icons')).end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
        const fileRule = config.module.rule('file')
        fileRule.uses.clear()
        fileRule
            .test(/\.svg$/)
            .exclude.add(path.resolve(__dirname, './src/icons'))
            .end()
            .use('file-loader')
            .loader('file-loader')
    }
}



//或者
const resolve = dir => path.join(__dirname, dir)

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

使用

           <div>
              <svg-icon iconClass="calender" />
              <span>可报名</span>
            </div>


           //icon-class的值直接是svg的文件名

 vue3

src/icons/index.js

import { readFileSync, readdirSync } from 'fs'

let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g

// 查找svg文件
function svgFind(e) {
  const arr = []
  const dirents = readdirSync(e, { withFileTypes: true })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
    else {
        const svg = readFileSync(e + dirent.name)
                    .toString()
                    .replace(clearReturn, '')
                    .replace(svgTitle, ($1, $2) => {
                            let width = 0,
                                height = 0,
                                content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
                                    if (s2 === 'width') width = s3
                                    else if (s2 === 'height') height = s3
                                    return ''
                                })
                if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`
                return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${content}>`
        }).replace('</svg>', '</symbol>')
        arr.push(svg)
    }
  }
  return arr
}

// 生成svg
export const createSvg = (path, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = svgFind(path)
  return {
    name: 'svg-transform',
    transformIndexHtml(dom) {
        return dom.replace(
            '<body>',
            `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">${res.join('')}</svg>`
        )
    }
  }
}

src/icons/index.vue

<template>
    <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
        <use :xlink:href="iconName"></use>
    </svg>
</template>

<script setup>
import { computed } from 'vue'
const props = defineProps({
    name: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: ''
    }
})
const iconName = computed(() => `#icon-${ props.name }`)
const svgClass = computed(() => {
    if(props.name) return `svg-icon icon-${ props.name }`
    return 'svg-icon'
})
</script>

<style scoped lang='scss'>
.svg-icon{
    width: 1em;
    height: 1em;
    fill:currentColor; 
    vertical-align: baseline;
    &:focus{
        outline:0
    }
}
</style>

src/main.js

import svgIcon from './icons/index.vue'
createApp(App).component('svg-icon', svgIcon)

vite.config.js

import { defineConfig } from 'vite'
import { resolve } from "path";
import vue from '@vitejs/plugin-vue'
import { createSvg } from './src/icons/index'

export default defineConfig({
  plugins: [vue(), createSvg('./src/icons/svg/')],
  resolve: {
    alias: {
      '@': resolve("./src"),
    },
  },
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值