在 Vue.js 中使用 SVG 图标

虽然基于字体的图标在一两年前统治了世界,但嵌入式SVG图标从那时起就成为了最佳方式将图标纳入您的应用程序((https://css-tricks.com/icon-fonts-vs-svg/))。

让我们从它开始,我们会?

安装 & 设置

vue-svgicon 可以通过 Yarn 或 NPM 按预期安装:

1# Yarn
2$ yarn add vue-svgicon -D
3
4# NPM
5$ npm install vue-svgicon --save-dev

接下来,我将使用材料设计图标集(https://github.com/Templarian/MaterialDesign/tree/master/icons/svg),其中一个最大的集合,几乎有2000个单独的图形,基于谷歌的设计指南,但主要来自社区。

将这些.svg 文件粘贴到您的项目根的 svg 图标文件夹中(在 src 目录之外)。

现在, vue-svgicon 需要将所有 svg 图标文件转换成可以单独加载的.js 文件,所以让我们为我们添加一个快速的 NPM 脚本来做。

1[label package.json]
2{
3  ...
4  "scripts": {
5    ...
6    "generate-icons": "vsvg -s ./svg-icons -t ./src/compiled-icons"
7  }
8  ...
9}

然后发出命令 npm run generate-icons. 这将输出编译的图标在 src/compiled-icons/[icon-name].js

使用

现在我们需要在我们的应用程序中加载图标. 将 vue-svgicon 插件添加到您的主要 Vue 应用程序文件:

1[label src/main.js]
2...
3import VueSVGIcon from 'vue-svgicon'
4
5Vue.use(VueSVGIcon)
6
7...

现在,我们可以通过使用<svgicon>元素将图标加载到我们的组件中,并导入我们正在使用的图标,作为一个很好的奖励,通过这种方式使用SVG图标,我们几乎没有任何努力才能在应用中加载我们所需要的图标。

 1[label src/ExampleComponent.vue]
 2<template>
 3  <div>
 4    <span>Icon Demonstration:</span>
 5    <!-- You can tweak the width, height, and color of the icon. -->
 6    <svgicon icon="menu" width="22" height="18" color="#0f2"></svgicon>
 7  </div>
 8</template>
 9
10<script>
11// If you really, really need to, you can import the whole iconset in your main.js file with `import ./compiled-icons`.
12import './compiled-icons/menu';
13</script>

有几个其他干净的小技巧Vue-svgicon有它的袖子,了解更多在官方存储库(https://github.com/MMF-FE/vue-svgicon)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus