如何在vue中优雅的使用svg

辰漪
2022-03-22 / 1 评论 / 335 阅读 / 正在检测是否收录...

1. svg-sprite-loader

npm install svg-sprite-loader --save

2. 在src中新建文件夹icons

icons/svg 存放svg图标
icons/index.js 全局注册svg组件,导入所有svg图标
l11l9x1t.png

// icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'// svg component
// register globally
Vue.component('SvgIcon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

3. 创建svg组件

// src/components/ScgIcon/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>

4. 在vue.config.js中使用loader

const path = require('path')
function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  devServer: {
    port: 8080,
    open: true
  },
  chainWebpack (config) {
    // set 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()
  }
}

5. 在main.js中导入icons/index.js

// main.js
import '@/icons/index' // svg

6. 在页面中使用组件

<SvgIcon iconClass="eye-open"></SvgIcon>

直接使用svg文件名作为iconClass

0
选择打赏方式:
微信

评论 (1)

取消
  1. 头像
    123
    Windows 10 · Google Chrome

    4

    回复