类似字体的SVG图标系统,用于VUE
在vue.js中管理图标可能很棘手。图标字体很方便,但缺乏自定义灵活性,由于其二进制性质,版本控制可能是一场噩梦。 SVG提供了出色的解决方案,但是保持易用性和有效的管理需要进行周到的方法。
本文介绍了vue.js应用程序的理想SVG图标系统,重点介绍了简单性和可维护性:
- 图标添加/删除:只需从指定文件夹中添加或删除SVG即可。
-
用法:使用直接语法的模板中使用图标
<svg-icon icon="rocket"></svg-icon>
。 -
样式:使用CSS
font-size
和颜色属性的比例和color
图标,模仿图标字体行为。 - 优化:避免使用同一图标多个实例的SVG代码重复。
- WebPack集成:无需更改WebPack配置。
该系统是使用两个小型单文件的VUE组件构建的,需要:
- WebPack:假定使用VUE CLI。
-
svg-inline-loader
:可通过npm install svg-inline-loader --save-dev
。该装载机清理了SVG代码的不必要部分。
SVG Sprite组件( SvgSprite.vue
)
为了防止SVG代码重复,我们创建了一个SVG Sprite,这是一个隐藏的SVG,其中包含所有其他SVG图标。图标是通过<use></use>
引用图标ID的标签:<svg><use xlink:href="#rocket"></use></svg>
。 SvgSprite
组件实现了以下操作:
<template> <svg height="0" style="display: none;" v-html="$options.svgSprite" width="0"></svg> </template> <script> const svgContext = require.context( '!svg-inline-loader?' 'removeTags=true' // Remove title tags, etc. '&removeSVGTagAttrs=true' // Remove attributes '&removingTagAttrs=fill' // Remove fill attributes '!@/assets/icons', // Icon directory true, // Search subdirectories /\w \.svg$/i // Only include SVG files ); const symbols = svgContext.keys().map(path => { const id = path.replace(/^\.\/(.*)\.\w $/, '$1'); // Extract ID from filename const content = svgContext(path); // Get SVG content return content.replace('<svg', `<symbol id="${id}"`).replace('svg>', 'symbol>'); // Convert to symbol }); export default { name: 'SvgSprite', svgSprite: symbols.join('\n'), // Concatenate symbols }; </script>
该模板包括一个隐藏<svg></svg>
其内容由$options.svgSprite
动态生成的元素。脚本使用require.context
带有svg-inline-loader
来处理SVG,删除了不必要的标签和属性。然后,它将每个SVG转换为<symbol></symbol>
元素,添加一个唯一的ID。
将此组件放在App.vue
文件的顶部。
图标组件( SvgIcon.vue
)
使用SvgIcon
组件更简单<use></use>
标签以参考Sprite的图标:
<template> <svg class="icon" :class="{ 'icon-spin': spin }"> <use :xlink:href="`#${icon}`"></use> </svg> </template> <script> export default { name: 'SvgIcon', props: { icon: { type: String, required: true }, spin: { type: Boolean, default: false }, }, }; </script> <style scoped> svg.icon { fill: currentColor; height: 1em; margin-bottom: 0.125em; vertical-align: middle; width: 1em; } svg.icon-spin { animation: icon-spin 2s infinite linear; } @keyframes icon-spin { from { transform: rotate(0deg); } to { transform: rotate(359deg); } } </style>
CSS样式的图标像图标字体一样表现,从而实现了简单的颜色和尺寸调整。 spin
道具增加了动画。
在main.js
中注册此组件:
从“ vue”导入vue 从'@/components/svgicon.vue'导入svgicon vue.component('svg-icon',svgicon)
该系统为您的vue.js应用程序中的SVG图标提供了干净,高效且易于维护的解决方案。进一步的改进可能包括处理非方面的纵横比以及更广泛的框架/构建工具兼容性。
以上是类似字体的SVG图标系统,用于VUE的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

您是否曾经在项目上需要一个倒计时计时器?对于这样的东西,可以自然访问插件,但实际上更多

格子呢是一块图案布,通常与苏格兰有关,尤其是他们时尚的苏格兰语。在Tartanify.com上,我们收集了5,000多个格子呢
