elementui svg
ElementUI 中使用 SVG 的方法
在 ElementUI 中直接使用 SVG 可以通过以下方式实现:
自定义图标组件 创建一个 Vue 组件来封装 SVG 内容:
<template>
<svg :class="className" :width="width" :height="height">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
width: {
type: String,
default: '1em'
},
height: {
type: String,
default: '1em'
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}`
}
}
}
</script>
配置 SVG sprite 在项目中创建 svg 文件夹存放 SVG 文件,使用 webpack 的 svg-sprite-loader 处理:
// 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]'
})
.end()
}
}
自动导入 SVG 文件 创建自动导入脚本:

// src/icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
req.keys().map(req)
在 ElementUI 组件中使用
<template>
<el-button>
<svg-icon icon-class="user" /> 用户
</el-button>
</template>
替代方案:使用 el-icon 的自定义 SVG
ElementUI 2.x 版本支持通过 el-icon 使用 SVG:

<template>
<el-icon :size="20">
<path d="M7 10l5 5 5-5z" />
</el-icon>
</template>
动态颜色控制
通过 CSS 变量控制 SVG 颜色:
.svg-icon {
color: var(--icon-color, currentColor);
}
在组件中动态修改:
<template>
<svg-icon
:style="{ '--icon-color': active ? '#409EFF' : '#C0C4CC' }"
icon-class="edit"
/>
</template>
性能优化建议
对于大量使用 SVG 的场景,建议:
- 使用 SVG sprite 减少 HTTP 请求
- 对静态 SVG 进行 gzip 压缩
- 考虑使用 CDN 加载常用 SVG
- 对动态 SVG 使用 vue-awesome 等专门库
以上方法可以根据具体项目需求选择组合使用,ElementUI 本身不限制 SVG 的使用方式,这些方案都能良好兼容其组件体系。






