icon处理方案:SvgIcon(学习笔记)

327 阅读1分钟

SvgIcon组件应拥有什么能力

  1. 能显示 element-plus 图标
  2. 显示自定义 svg 图标(外部 svg 链接和本地 svg 图标)

第一步 创建svg-icon 组件

  1. 在 components 文件夹下创建 SvgIcon/index.vue 代码结构:
<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    :class="className"
  />
  <svg v-else class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>
<script setup>
import { defineProps, computed } from 'vue'
import { isExternal as external } from '@/utils/validate'
const props = defineProps({
  // icon 图标
  icon: {
    type: String,
    required: true
  },
  // 图标类名
  className: {
    type: String,
    default: ''
  }
})

/**
   * 判断是否为外部图标
   */
const isExternal = computed(() => external(props.icon))
/**
   * 外部图标样式
   */
const styleExternalIcon = computed(() => ({
  mask: `url(${props.icon}) no-repeat 50% 50%`,
  '-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))
/**
   * 项目内图标
   */
const iconName = computed(() => `#icon-${props.icon}`)
</script>

第二步 使用 svg-icon 组件

<svg-icon icon="https://res.lgdsunday.club/user.svg"></svg-icon>

第三步 处理内部svg显示

  1. 准备好svg 图标
  2. 创建a.js 文件 (处理本地 svg 图标的导入)
import SvgIcon from '@/components/SvgIcon'

// https://webpack.docschina.org/guides/dependency-management/#requirecontext
// 通过 require.context() 函数来创建自己的 context
const svgRequire = require.context('./svg', false, /\.svg$/)
// 此时返回一个 require 的函数,可以接受一个 request 的参数,用于 require 的导入。
// 该函数提供了三个属性,可以通过 require.keys() 获取到所有的 svg 图标
// 遍历图标,把图标作为 request 传入到 require 导入函数中,完成本地 svg 图标的导入
svgRequire.keys().forEach(svgIcon => svgRequire(svgIcon))

export default app => {
  app.component('svg-icon', SvgIcon)
}
  1. main.js 引入a.js
import installIcons from './a.js'
installIcons(app)
  1. 使用 svg-sprite-loader 处理 svg 图标(webpack中专门处理 svg 的loader)
  • npm i --save-dev svg-sprite-loader@6.0.9
  • 创建 vue.config.js 文件,做如下配置:
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}
// https://cli.vuejs.org/zh/guide/webpack.html#%E7%AE%80%E5%8D%95%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F
module.exports = {
  chainWebpack(config) {
    // 设置 svg-sprite-loader
    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()
  }
}

至此 本地 svg 可显示。 svg-icon组件封装完成。