Two examples of using icons in Vue3

Two examples of using icons in Vue3

Technology stack and version Vite2 + Vue3 + fontAwesome5

The way to use Icon in Vue3, fontAwesome is simple and easy to use, but sometimes the desired icon is missing. Using the svg method, you can directly download and use whatever you want. The types are more complete, and there is basically no icon that does not meet your needs. However, it is not as easy as fontAwesome, and you have to download the corresponding picture every time.

1. Use SVG

a Download the SVG image you want to use and save it to the src/icons folder

b Install the loader that depends on fs and svg

Command: npm install svg-sprite-loader

Command: npm install --save fs

c Create a template file index.vue

Template file code

<template>
    <svg :class="svgClass" v-bind = "$attrs">
        <use :xlink:href="iconName"></use>
    </svg>
</template>


<script setup>

import { defineProps, computed } from "vue";

const props = defineProps({
    name: {
      type: String,
      required: true
    },
    color:
      type: String ,
      default: '',
    }
})

const iconName = computed(()=>`#icon-${props.name}`);
const svgClass = computed(()=> {
    // console.log(props.name,'props.name');
    if (props.name) {
        return `svg-icon icon-${props.name}`
    }
      return 'svg-icon'
});

</script>

<style scoped lang ="scss">
    .svg-icon{
        width: 3em;
        height: 3em;
        fill: currentColor;
        border: solid 2px red;
        vertical-align: middle;
    }
</style>>

d Global registration main.js

import { svgIcon } from './components'
.component('svg-icon',svgIcon)

e Create an import processing function and create svgBulider.js in plugins

Code

import { readFileSync, readdirSync } from 'fs'


let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g

const hasViewBox = /(viewBox="[^>+].*?")/g

const clearReturn = /(\r)|(\n)/g

function findSvgFile(dir) {
  const svgRes = []
  const dirents = readdirSync(dir, {
    withFileTypes: true
  })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) {
      svgRes.push(...findSvgFile(dir + dirent.name + '/'))
    } else {
      const svg = readFileSync(dir + dirent.name)
        .toString()
        .replace(clearReturn, '')
        .replace(svgTitle, ($1, $2) => {
        
          let width = 0
          let height = 0
          let content = $2.replace(
            clearHeightWidth,
            (s1, s2, s3) => {
              if (s2 === 'width') {
                width = s3
              } else if (s2 === 'height') {
                height = s3
              }
              return ''
            }
          )
          if (!hasViewBox.test($2)) {
            content += `viewBox="0 0 ${width} ${height}"`
          }
          return `<symbol id="${idPerfix}-${dirent.name.replace(
            '.svg',
            ''
          )}" ${content}>`
        })
        .replace('</svg>', '</symbol>')
      svgRes.push(svg)
    }
  }
  return svgRes
}

export const svgBuilder = (path, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = findSvgFile(path)
  
  return {
    name: 'svg-transform',
    transformIndexHtml(html) {
      return html.replace(
        '<body>',
        `
          <body>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
              ${res.join('')}
            </svg>
        `
      )
    }
  }
}

f Modify the configuration file and import svgBulider into the configuration file

Modify vite.config.js

import { svgBuilder } from './src/plugins/svgBuilder'; '

export default defineConfig({
plugins: [
      vue(),
      //Call the corresponding function to process svg svgBuilder('./src/icons/') //The corresponding folder, otherwise it cannot be found]
})

g Using SVG

Core part

  <svg-icon name="questionmark" />//name Take your svg image

2. Use fontAwesome

a npm install dependencies

$ npm i --save @fortawesome/fontawesome
$ npm i --save @fortawesome/vue-fontawesome

$ npm i --save @fortawesome/fontawesome-free-solid
$ npm i --save @fortawesome/fontawesome-free-regular
$ npm i --save @fortawesome/fontawesome-free-brands

b mian.js global registration

    //Import on demand import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
    import { library } from '@fortawesome/fontawesome-svg-core'
    import { faAd } from '@fortawesome/free-solid-svg-icons'
    
    import { faAddressBook } from '@fortawesome/free-solid-svg-icons'
    
    library.add(faAddressBook)
    // Import all import { fas } from '@fortawesome/free-solid-svg-icons'
    import { fab } from '@fortawesome/free-brands-svg-icons'
    library.add(fas,fab)
    
    .component('font-awesome-icon', FontAwesomeIcon)
    

c Use

    //Use of on-demand import<font-awesome-icon icon="address-book" class="fa-spin fa-lg"/>
    //Use of global import <font-awesome-icon :icon="['fas','address-book']" />

3 Sources

Source fontAwesome https://www.jb51.net/article/228944.htm

Source svg https://www.jb51.net/article/228948.htm

4 Conclusion

Determine the corresponding technology stack and version, follow the steps, and there will be no problem.

This concludes this article about two ways to use icons in Vue3. For more relevant content about using icons in Vue3, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of how to use element-plus in Vue3
  • Detailed explanation of the process of using Icon icons globally in element-plus in Vue3

<<:  Introduction and architecture of Apache Arrow, a high-performance data format library package on JVM (Gkatziouras)

>>:  Implementation of Grid common layout

Recommend

Example of adding music video to HTML page

1. Video tag Supports automatic playback in Firef...

Analysis and application of irregular picture waterfall flow principle

The layout problem of irregular picture walls enc...

How to add Nginx to system services in CentOS7

Introduction After compiling, installing and solv...

How to build mysql master-slave server on centos7 (graphic tutorial)

This article mainly introduces how to build a MyS...

Web Design: Script Materials Reconstruct User Experience

<br />Original text: http://blog.rexsong.com...

Detailed explanation of XML syntax

1. Documentation Rules 1. Case sensitive. 2. The a...

js to realize web music player

This article shares simple HTML and music player ...

Nginx access log and error log parameter description

illustrate: There are two main types of nginx log...

Introduction to vim plugin installation under Linux system

Table of contents Install vim plugin manager Add ...

Specific method to add foreign key constraints in mysql

The operating environment of this tutorial: Windo...

A Brief Analysis of MySQL Connections and Collections

Join query A join query refers to a matching quer...

Linux C log output code template sample code

Preface This article mainly introduces the releva...

Implementation of Docker CPU Limit

1. --cpu=<value> 1) Specify how much availa...

Example of horizontal arrangement of li tags in HTMl

Most navigation bars are arranged horizontally as...