VUE 中使用SVG

1.安裝?svg-sprite-loader svgo

npm i?svg-sprite-loader svgo

2.創(chuàng)建SvgIcon組件

<template>

? <svg :class="svgClass" aria-hidden="true">

? ? <use :xlink:href="iconName"></use>

? </svg>

</template>

<script type="text/ecmascript-6">

export default {

? name: 'svg-icon',

? props: {

? ? iconClass: {

? ? ? type: String,

? ? ? required: true

? ? },

? ? className: {

? ? ? type: String

? ? }

? },

? computed: {

? ? iconName () {

? ? ? return `#icon-${this.iconClass}`

? ? },

? ? svgClass () {

? ? ? if (this.className) {

? ? ? ? return 'svg-icon ' + this.className

? ? ? } else {

? ? ? ? return 'svg-icon'

? ? ? }

? ? }

? }

}

</script>

<style>

.svg-icon {

? width: 1em;

? height: 1em;

? vertical-align: -0.15em;

? fill: currentColor;

? overflow: hidden;

}

</style>


3.新增svgicons/index.js文件和svg文件夾,并index.js增加如下代碼

import Vue from 'vue'

import SvgIcon from './SvgIcon'

Vue.component('svg-icon', SvgIcon)

const requireAll = requireContext => requireContext.keys().map(requireContext)

const req = require.context('./svg', false, /\.svg$/)

requireAll(req)

4.在main.js里面進(jìn)行引入

import '@/svgIcons'

6、若為vue2.0則在webpack.base.conf.js修改相關(guān)配置規(guī)則(include和exclude部分)

module: {

? ? rules: [

...

{

? ? ? ? test: /\.svg$/,

? ? ? ? loader: 'svg-sprite-loader',

? ? ? ? include: [resolve("src/svgIcons/svg")], // 把去掉的svg文件夾include進(jìn)來(lái)

? ? ? ? options: {

? ? ? ? ? symbolId: 'icon-[name]'

? ? ? ? }

? ? ? },

? ? ? {

? ? ? ? test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,

? ? ? ? loader: 'url-loader',

? ? ? ? exclude: [resolve("src/svgIcons/svg")],?// 去除你存放svg的那個(gè)文件夾,改用svgo-loader處理

? ? ? ? options: {

? ? ? ? ? limit: 10000,

? ? ? ? ? name: utils.assetsPath('img/[name].[hash:7].[ext]')

? ? ? ? }

? ? ? },

...

? ? ]

? },


7.若是vuecli3 則vue.config.js 文件配置

// 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()


8.使用

<svg-icon icon-class="update" size="40"></svg-icon>

?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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