vue cli3使用svg-sprite-loader

iconfont symbol對比svg-sprite-loader

iconfont symbol在SVG使用上簡單,但是對于后期修改不方便。
這是一種全新的使用方式,應(yīng)該說這才是未來的主流,也是平臺目前推薦的用法。相關(guān)
目前symbol方式的iconfont:

  • 支持多色圖標(biāo)了,不再受單色限制。
  • 通過一些技巧,支持像字體那樣,通過font-size,color來調(diào)整樣式。
  • 兼容性較差,支持 ie9+,及現(xiàn)代瀏覽器。
  • 瀏覽器渲染svg的性能一般,還不如png。
    使用iconfont的symbol方法

具體操作步驟

  1. 首先在iconfont官網(wǎng)批量下載svg圖片,可以操作


    image.png

    image.png

    image.png
  1. 將下載好的SVG放在目錄src/icons/svg
  2. 安裝svg-sprite-loader
yarn add svg-sprite-loader --dev
  1. 配置vue.config.js,加入一段代碼
const path = require('path')
function resolve(dir) {
 return path.join(__dirname, '.', dir)
}

module.exports = {
 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]'
            })
    }
}

5.在compoents下新建SvgIcon組件index.vue


image.png

<template>
  <svg :class="svgClass" aria-hidden="true">
    <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>

  1. 在src/icons下新建index.js


    image.png
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component

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

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

  1. 在main.ts下添加import '@/icons'


    image.png

OK,完成以上配置即可添加svg

<svg-icon icon-class="zhuye" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容