Iconfont usage in Vue

The development process of the icon library, the importance of the iconfont icon library (commonly used in projects)

For the front end, the development of icons can be described as changing with each passing day. From img tags, to sprite images, to font icons, svg, and even svg has a solution similar to sprite images, svg-sprite-loader. In project practice, UI libraries such as bootstrap, font-awesome, and element-ui are basically equipped with font icons as standard.

1. Iconfont - icon management tool

An icon management platform built by the Alimama MUX team under Alibaba.

This is an online tool specially built for designers and front-end developers. Designers upload icons to Iconfont, and can customize and download icons in various formats, and can also convert icons into fonts, which is convenient for front-end engineers to adjust and use freely.

Through this free tool, designers can not only browse and download a large number of icon works of excellent designers, but also manage and display the icons they design. It has become an essential tool for many UI designers and front-end developers in their daily work.

A large number of high-quality original icon libraries

features

  1. Vector icon online storage management.

  2. A large number of icons drawn by designers can be uploaded, which solves the pain point of very difficult management and finding icons;

  3. According to the project management icon, it supports custom size and color. Whether you are a front-end engineer or a UI designer, you no longer have to cut and move bricks hard. You can download it on the platform for the size you need;

  4. For developers, they can manage the required vector icons in the form of projects, generate vector icons controlled by css fonts on the web with one click, and support calling on web/h5/mini-programs/Apps. It is easy and convenient to use, and then There is no need to use blurry picture icons;

  5. For designers, there are thousands of designers sharing their own icons on the platform, which is definitely a sharp tool for icon design learning and inspiration.

Two, Iconfont - basic use

Three ways to introduce iconfont: Unicode, Font class, Symbol.

1. Unicode method (not recommended)

use online

1) Introduce online fonts into index.scss

@font-face {  font-family: 'iconfont';  /* project id 1254715 */    
src: url('//at.alicdn.com/t/font_1254715_s1khj1whikd.eot');    
src: url('//at.alicdn.com/t/font_1254715_s1khj1whikd.eot?#iefix') format('embedded-opentype'),    
url('//at.alicdn.com/t/font_1254715_s1khj1whikd.woff2') format('woff2'),    
url('//at.alicdn.com/t/font_1254715_s1khj1whikd.woff') format('woff'),    
url('//at.alicdn.com/t/font_1254715_s1khj1whikd.ttf') format('truetype'),    
url('//at.alicdn.com/t/font_1254715_s1khj1whikd.svg#iconfont') format('svg');}
复制代码

2) Use in the page

It is very unfriendly to use. It uses unicode code representation. To use icons, you must go to the iconfont project to query the unicode code.

<template>    
    <div>        
        <i class="iconfont">&#xe7ee;</i>        
        <i class="iconfont">&#xe7ed;</i>        
        <i class="iconfont">&#xe7ec;</i>        
        <i class="iconfont">&#xe7eb;</i>    
    </div>
</template>
复制代码

local use

Sometimes the network is not so powerful, or it is an intranet environment, so don't consider using online citations.

1) For local use, you need to download the font library and put it in the project.

2) Define the following code in the global style file

@font-face {  font-family: "iconfont";  
src: url('../fonts/iconfont.eot'); /* IE9*/  
src: url('../fonts/iconfont.eot#iefix') format('embedded-opentype'), /* IE6-IE8 */  
url('../fonts/iconfont.woff') format('woff'), /* chrome, firefox */  
url('../fonts/iconfont.woff2') format('woff2'), /* chrome, firefox */  
url('../fonts/iconfont.ttf') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/  
url('../assets/fonts/iconfont.svg#iconfont') format('svg'); /* iOS 4.1- */}
.iconfont {  font-family: "iconfont" !important;  font-size: 16px;  
font-style: normal;  
-webkit-font-smoothing: antialiased;  
-moz-osx-font-smoothing: grayscale;}
复制代码

3) How to use

It is the same as the online reference method, which uses unicode codes to display icons.

<template><i class="iconfont">&#xe7ee;</i></template>
复制代码

*Summarize

1) The compatibility is the best, supporting ie6+, and all modern browsers.

2) Support dynamic adjustment of icon size, color, etc. by font.

3) Because it is a font, it does not support multi-color. You can only use monochrome icons on the platform, even if there are multi-color icons in the project, they will be automatically decolorized.

2. Font class method (friendly)

A more friendly encapsulation, similar to font-awesome, as long as we use the class, we can call the icon. The principle is to use the before pseudo-element to display icons.

use online

It's super simple, just generate the code online and refer to the online css file to use it.

1) Referenced in index.html

<link rel="stylesheet" href="//at.alicdn.com/t/font_1261797_48wm20jf8z.css">
复制代码

2) The font icon can be used in the project

<template>    
    <i class="iconfont cl-icon-fold"></i>    
    <i class="iconfont cl-icon-delete-solid"></i>
</template>
复制代码

local use

Similar to the unicode method, download the code to the local. Because I use scss to manage styles, I need to extract key parts from the downloaded code. In addition to referencing the font library, copy all the before pseudo-elements defined in iconfont.css to your own scss file.

@font-face {  
    font-family: "iconfont";  
    src: url('../fonts/iconfont.eot'); /* IE9*/  
    src: url('../fonts/iconfont.eot#iefix') format('embedded-opentype'), /* IE6-IE8 */  
    url('../fonts/iconfont.woff') format('woff'), /* chrome, firefox */  
    url('../fonts/iconfont.woff2') format('woff2'), /* chrome, firefox */  
    url('../fonts/iconfont.ttf') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/  
    url('../assets/fonts/iconfont.svg#iconfont') format('svg'); /* iOS 4.1- */}
.iconfont {  font-family: "iconfont" !important;  
font-size: 16px;  font-style: normal;  
-webkit-font-smoothing: antialiased;  -moz-osx-font-smoothing: grayscale;}// 列了一部分举例
.cl-icon-user:before {  content: "\e64b";}
复制代码

*Summarize

1) Good compatibility, support ie8+, and all modern browsers.

2) Compared with unicode, the semantics are clear, and writing is more intuitive. It is easy to tell what the icon is.

3) Because the class is used to define the icon, when the icon needs to be replaced, only the unicode reference in the class needs to be modified.

4) However, because the font is still used in essence, multi-color icons are still not supported.

**suggestion

Since adding a new icon requires re-generating the code on iconfont.cn, this method is not very convenient, but it is still much more advanced than unicode. According to my experience, it is recommended that when debugging, you should use the online method first, and then download it to use locally after the debugging is completed and confirmed to be correct, which will greatly help improve efficiency.

3. Symbol mode (supports multi-color icons)

The symbol of svg provides functions similar to sprite images, which makes the use of svg easier and can also meet the needs of making icon systems.

use online

1) Select the symbol mode in the iconfont project and generate js code online

2) Introduce this js file in index.html

<script src="//at.alicdn.com/t/font_1254715_oewlgci0ut.js"></script>
复制代码

The function of this js is to generate svg symbol in the document

3) Use the svg icon in the page through the use tag. The value of xlink:href can be set to the id of the corresponding symbol.

<svg aria-hidden="true">    <use xlink:href="#test-icon-word-ext"></use> </svg>
复制代码

local use

The same is true for local use, mainly relying on this js file generated online, open the link of the online js file in an empty browser tab, you can get its content, then copy the content, name a js file yourself, and put it Put it in the static resource directory of the local project and just reference it.

4. Icon automatic management (must see)

The icons of the above three usage methods all rely on iconfont to be managed in the form of a project. If an icon is added to the project, the icon-related resources must be regenerated and updated and introduced in the code. Icon management is not very convenient.

svg-sprite-loader + require.context solves this problem elegantly.

The project is built using Vue CLI

Reference steps

1) Install svg-sprite-loader

npm install svg-sprite-loader  -save-dev
复制代码

2) Create a new svg folder under the src directory, where all svg files are stored.

3) Configure the corresponding svg-sprite-loader rules for loading svg files in the vue.config.js file

chainWebpack: config => {        
    config.module.rules.delete('svg'); //重点:删除默认配置中处理svg,        
    config.module            
    .rule('svg-sprite-loader')            
    .test(/\.svg$/)            
    .include.add(resolve('src/assets/icons/svg')) //处理svg目录            
    .end()            
    .use('svg-sprite-loader')            
    .loader('svg-sprite-loader')            
    .options({ symbolId: 'icon-[name]',});    }
复制代码

Instructions

1) Encapsulate the SvgIcon.vue component

<template>  
    <svg :class="svgClass" aria-hidden="true" v-on="$listeners">    
    <use :xlink:href="iconName" />  
    </svg>
</template>
<script>
    export default {  name: 'SvgIcon',  
        props: {    
            svgName: {      
                type: String,      
                required: true    
            },    
            className: {      
                type: String,      
                default: ''    
            }  
         },  
        computed: {    
            iconName() {   
                return `#icon-${this.svgName}`    
          },    
        svgClass() {      
            if (this.className) {        
                return 'svg-icon ' + this.className      
            }  else { return 'svg-icon' }    }  }}
</script>
复制代码

2. Register SvgIcon as a global component in main.js

import svgIcon from './components/SvgIcon.vue'Vue.component('svg-icon', svgIcon)
复制代码

3) Globally load all svg files in main.js, no need to import them every time

// 全局加载svg,不用每次都importconst req = require.context('./svg', false, /\.svg$/)const requireAll = requireContent => requireContent.keys().map(requireContent)requireAll(req)
复制代码

3. Iconfont - Project Practice

1. Pain points

Icon management is an important but easily overlooked link in the process of converting design drafts to code.

The solution to the icon problem in the actual business code, such as exporting files in png, svg format, directly referencing them as static resources in the project, or uploading them to CDN as external link references. Obviously, there are some small problems in these solutions:

1) In terms of user experience , including blurred display on high-resolution screens, additional http requests, asynchronous loading causing page jitter, etc.;

2) In terms of development experience , including the inability to control the style through CSS so as to be consistent with the text, it is difficult to reuse and update, etc.

For the team, Taobao's free `iconfont` website is undoubtedly a fast solution : upload icon—generate project—one-click download, very convenient. However, several issues prevent it from being an enterprise-grade solution:

1) One is that there is no connection between projects, and the same icon cannot be reused and updated uniformly;

2) One is that the enterprise account cannot be strongly bound, and it is uncontrollable during team collaboration and personnel change and handover;

3) The last one is the copyright issue of icons, everyone can use the icons uploaded to the platform by everyone for free, which may not be what the company wants.

2. Expected goals and solutions (refer to Zhuan FE solution)

After the platform was launched, we also promoted it to the UI team and the FE team respectively, and clarified the responsibilities of all parties to better cooperate with each other. Such a workflow is very clear:

1) UI is responsible for the unified management of icon resources - uploading icons to the platform, and distinguishing business lines through different "big libraries" to form an icon pool;

2) FE only needs to care about its own projects - pick icons from the pool, generate projects, export external links, and import them into projects for use.

  • icon: Unified processing of uploaded svg files, saving complete path information;

  • Large library: establish a mapping relationship with icons, group, edit, and update icons, mainly for UI;

  • Project: It also establishes a mapping relationship with icons, facing FE, selects icons to create projects, and is responsible for generating external links, downloading icons, etc.;

  • User: Connect with the enterprise WeChat scan code login system, responsible for role and authority management;

  • Log: record the upload, review, and edit of icons; the change of personnel roles; the update of projects and other log information, so that all operations of the system can be traced;

  • svg2ttf: parse the svg path, convert it into general font files such as ttf woff eot, and package and upload to CDN;

3. Project implementation (reflection itself, solution)

1) The UI is responsible for the unified management of icon resources ——upload icons to the Iconfont platform, and form icon pools according to business lines;

2) FE is responsible for the unification of icon code resources - select icons from the pool, generate projects, export external links, and import them into projects for use.

It has achieved remarkable results in improving the cooperation efficiency of UI team and FE team, improving the maintainability of iconfont resources and the final user experience.

4. Iconfont - a new color font icon

Colors fonts (or chromatic fonts) is a font technology that allows multiple colors to be used in each glyph. It can be used not only in the design of icons and emojis, but also in ordinary text fonts.

color font format

Currently, there are mainly the following formats that support color fonts, all of which are part of the OpenType specification:

SVG: A vector font standard led by Adobe and Mozilla, the full name is OpenType SVG (hereinafter referred to as OT-SVG). It contains not only standard TrueType or CFF glyph information, but also optional SVG data, allowing to define colors, gradients and even animation effects for the font. Color matching information from the SVG standard will also be stored in the CPAL table. Note: Apple's implementation follows the W3C's SVG Native specification, which is a subset of SVG 1.1.

COLR/CPAL (version 0): Microsoft-led vector font standard. Among them, COLR records layer data, CPAL records color matching information, and its support is integrated in Windows 8.1 and later versions (this version does not support gradients).

CBDT/CBLC: Bitmap font standard led by Google. Among them, CBDT records color bitmap data, and CBLC records bitmap positioning data, which is actually the color version of EBDT/EBLC.

SBIX: Apple-led standard for bitmap fonts, the format used by Apple Emoji. SBIX stands for Standard Bitmap Image Table, which contains PNG, JPEG or TIFF image information, and its support is integrated in macOS and iOS.

COLRv1 (version 1): An upgraded version based on the COLR/CPAL table promoted by Google, which supports gradients, affine transformations (Affine transformation) and multiple blending modes. It is currently in the OpenType 1.9 Alpha specification.

*how to use

1. Open a multi-color icon library, select several favorite icons and add them to the shopping cart.

2. Click the shopping cart button on the right to open the shopping cart floating layer.

3. In the floating layer of the shopping cart, click the New Item button, enter the item name, and click the OK button. Such a test color font icon project is built.

4. Then it will automatically jump to the newly created project, click "Project Settings" in the upper right corner.

5. Check the "Color" option in the font format, and click the "Save" button.

6. Click "No code yet, click here to generate", and after a while, the generation of colored fonts will be slightly slower.

7. After the generation is successful, there will be a "Preview Font" menu behind the online link button, open it to test the effect of the actual color font.

Design is great because of infinite imagination, and technology is the wings of imagination. Spread your wings and fly high, let us explore more interesting ideas together!

Guess you like

Origin blog.csdn.net/sinat_17775997/article/details/127344128