vue 使用svg圖標(biāo)

之前做項(xiàng)目中,使用的小圖標(biāo)都是使用字體圖標(biāo),現(xiàn)在這個(gè)項(xiàng)目因?yàn)楫吘剐?,就想使用svg來展示svg。因?yàn)樵趯W(xué)習(xí)的過程中,遇到了一些坑,就在這里跟大家分享一下。

1、創(chuàng)建svg-icon組件

<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>

2、讀取svg文件

在同一目錄下,新建index.js文件

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

3、存放svg圖片

在同一目錄下新建一個(gè)svg(任君修改)文件夾,用于存放svg圖片。

4、安裝依賴

npm i svg-sprite-loader --save

5、修改配置

配置一,針對(duì)vue-cli3之前的
webpack.base.config.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]")
    }
},

配置二,針對(duì)vue-cli3
vue.config.js

chainWebpack: config => {
        const svgRule = config.module.rule('svg')
        // 清除已有的所有 loader,如果你不這樣做,接下來的 loader 會(huì)附加在該規(guī)則現(xiàn)有的 loader 之后。
        svgRule.uses.clear()
        // 添加要替換的 loader
        svgRule.use('svg-sprite-loader').loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
    }

6、引入組件

我main.js里面引入了svg-icon組件,當(dāng)然也可以在上面我們寫的那個(gè)index.js文件上面全局注冊(cè)該組件

import SvgIcon from '@/components/SvgIcon/index.vue'// svg組件
Vue.component('svg-icon', SvgIcon)
import '@/components/SvgIcon/index.js'

7、使用 svg-icon

<svg-icon icon-class="404" />

8、介紹 require.contex

可能很多人跟我一樣,其他都很明白,除了 require.context這個(gè)不太理解,不知道是什么玩意,我查閱資料的過程中,我看到一個(gè)帖子,寫得特別清楚,就直接拿過用一下,為表示尊重,這是他原文的地址
https://segmentfault.com/a/1190000019723837

requireContext.png

只需一張圖片,清清楚楚,明明白白。

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

相關(guān)閱讀更多精彩內(nèi)容

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