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

JavaScript to implement simple carousel chart most complete code analysis (ES5)

This article shares the specific code for JavaScr...

How to set up ssh password-free login to Linux server

Every time you log in to the test server, you alw...

CSS uses radial-gradient to implement coupon styles

This article will introduce how to use radial-gra...

25 Tools to Improve Website Usability and Conversion Rates

For a website, usability refers to whether users c...

MYSQL stored procedures, that is, a summary of common logical knowledge points

Mysql stored procedure 1. Create stored procedure...

Drop-down menu and sliding menu design examples

I found a lot of websites that use drop-down or sl...

Difference between var and let in JavaScript

Table of contents 1. Scopes are expressed in diff...

Detailed explanation of HTML programming tags and document structure

The purpose of using HTML to mark up content is t...

The difference and usage of distinct and row_number() over() in SQL

1 Introduction When we write SQL statements to op...

How to set up Spring Boot using Docker layered packaging

The Spring Boot project uses docker containers, j...

Comprehensive analysis of MySql master-slave replication mechanism

Table of contents Master-slave replication mechan...

Solution to Element-ui upload file upload restriction

question Adding the type of uploaded file in acce...

A brief discussion on JavaScript throttling and anti-shake

Table of contents Throttling and anti-shake conce...

Detailed explanation of MySQL database triggers

Table of contents 1 Introduction 2 Trigger Introd...