1.Vue-自定义icon实现
在项目中引入了element-ui之后,发现其内置的icon有限,无法满足项目的需求,因此需自定义icon来实现需求。
- 在vue项目的components下新建SvgIcon目录,在SvgIcon目录下新建index.vue

插入代码:
| <template> |
| <svg class="svg-icon" aria-hidden="true"> |
| <use :xlink:href="iconName"></use> |
| </svg> |
| </template> |
| |
| <script setup> |
| import { defineProps, computed } from 'vue' |
| const props = defineProps({ |
| icon: { |
| type: String, |
| required: true |
| } |
| }) |
| |
| const iconName = computed(() => { |
| return `#icon-${props.icon}` |
| }) |
| </script> |
| |
| <style lang="scss" scoped> |
| .svg-icon { |
| width: 1em; |
| height: 1em; |
| vertical-align: -0.15em; |
| fill: currentColor; |
| overflow: hidden; |
| } |
| </style> |
| |
- 在src下建立一个icons文件夹,放一个svg文件的文件夹目录,以及新建index.js,全局定义组件

index.js全局组件
| import SvgIcon from '@/components/SvgIcon' |
| |
| const svgRequired = require.context('./svg', false, /\.svg$/) |
| svgRequired.keys().forEach((item) => svgRequired(item)) |
| |
| export default (app) => { |
| app.component('svg-icon', SvgIcon) |
| } |
- 安装webpack

- 安装svg-sprite-loader

- vue.config.js
| |
| |
| |
| |
| |
| const webpack = require('webpack'); |
| |
| const path = require('path') |
| function resolve(dir) { |
| return path.join(__dirname, dir) |
| } |
| |
| module.exports = { |
| lintOnSave: false, |
| |
| 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() |
| config |
| .plugin('ignore') |
| .use( |
| new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/) |
| ) |
| 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() |
| } |
| } |
| |
- main.js修改
| import SvgIcon from '@/icons' |
| |
| const app = createApp(App) |
| SvgIcon(app); |
| |
| app.use(store) |
| app.use(router) |
| app.use(ElementPlus) |
| app.mount('#app') |
| |
| |
| |
- 使用
| <template #prefix><svg-icon icon="user" /></template> |


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南