svg图标封装

PS:注意如果在iconfont上下载的SVG图标,请把fill="#ffffff"清除掉,不然自定义样式无法作用到图标上。

PS:webpack3及以下和webpack4配置略有不同, webpack4的SVG配置请参考


npm install -g svgo

svgo -f ./src/icons/svg

npm install svg-spribe-loader -D

配置build/webpack.base.conf.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]')

}

},

组件:svgicon.vue

、、、

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

、、、


src/icons/index.js

、、、

import Vue from 'vue'

import SvgIcon from '@/components/SvgIcon' // svg组件


// register globally

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


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

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

requireAll(req)

、、、

main.js

import ‘@/icons’

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容