Vue.js handles Icon icons through components

Vue.js handles Icon icons through components

Icon icon processing solution

The goal of this record is to record how to encapsulate icons other than element-plus into a component. I hope it can help me deal with icon problems at work.

Analysis shows that element-plus icons can be displayed through el-icon, while custom icons require a custom icon component to display custom svg icons.

Component Capabilities

  • Display external svg icon (external link)
  • Display the svg icon within the project

Icon component packaging ideas

Icon component for display

Create components/SvgIcon/index.vue :

<template>
    <div
        v-if="isExternal"
        :style="styleExternalIcon"
        class="svg-external-icon svg-icon"
        :class="className"
    />
    <svg v-else class="svg-icon" :class="className" aria-hidden="true">
        <use :xlink:href="iconName" rel="external nofollow" />
    </svg>
</template>
​
<script setup>
    import { isExternal as external } from '@/utils/validate'
    import { defineProps, computed } from 'vue'
    const props = defineProps({
        //icon icon: {
            type: String,
            required: true
        },
        // Icon class name className: {
            type: String,
            default: ''
        }
    })
    /**
     * Determine whether it is an external icon*/
    const isExternal = computed(() => external(props.icon))
    /**
     * External icon style */
    const styleExternalIcon = computed(() => ({
        mask: `url(${props.icon}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
    }))
    /**
     * Project icon */
    const iconName = computed(() => `#icon-${props.icon}`)
</script>
​
<style lang='scss' scoped>
    .svg-icon {
        width: 1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
    }
​
    .svg-external-icon {
        background-color: currentColor;
        mask-size: cover !important;
        display: inline-block;
    }
</style>
​

Determine whether the resource is an external resource

Create utils/validate.js :

/**
 * Determine whether it is an external resource*/
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

External svg icon display

By introducing the component svg-icon, icon passes the icon external link.

<span class="svg-container">
    <svg-icon icon="https://xxx.svg"></svg-icon>
</span>

Processing SVG icons in projects

  • Create an icons folder in the src directory of the project and import the svg icon file
  • Create an index.js file under icons

Files do two things

  • Import all svg icons
  • Complete the global registration of SvgIcon

The index.js code is as follows

Reference Document Dependency Management | webpack Chinese Documentation

import SvgIcon from '@/components/SvgIcon'
​
// Create your own context through require.context() function
const svgRequire = require.context('./svg', false, /\.svg$/)
// At this point, a require function is returned, which can accept a request parameter for the require import.
// This function provides three properties, and you can get all svg icons through require.keys() // Traverse the icons and pass the icons as requests to the require import function to complete the import of local svg icons svgRequire.keys().forEach(svgIcon => svgRequire(svgIcon))
​
export default app => {
 app.component('svg-icon', SvgIcon)
}

Globally registered project icons

Import this file into main.js

...
// Import svgIcon
import installIcons from '@/icons'
...
installIcons(app)
...

Use internal icon

// Username <svg-icon icon="user" />
// Password<svg-icon icon="password" />

Use svg-sprite-loader to process svg icons

svg-sprite-loader is a loader in webpack that specializes in processing svg icons

Install: npm i --save-dev [email protected]

Configure loader in vue.config.js file

const path = require('path')
function resolve(dir) {
 return path.join(__dirname, dir)
}
​
module.exports = {
 chainWebpack(config) {
   // Set up svg-sprite-loader
   config.module
     .rule('svg')
     .exclude.add(resolve('src/icons'))
     .end()
   config.module
     .rule('icons')
     .test(/\.svg$/)
     .include.add(resolve('src/icons'))
     .end()
     .use('svg-sprite-loader')
     .loader('svg-sprite-loader')
     .options({
       symbolId: 'icon-[name]'
     })
     .end()
 }
}

This will handle the internal svg icon.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Two examples of using icons in Vue3
  • Steps to customize icon in Vue
  • How to introduce icon icon into vue element project
  • How to use custom icon in Vue
  • How to introduce icon icons in Vue project

<<:  HTML marquee tag usage examples

>>:  Docker Compose installation and usage steps

Recommend

Implementation of mysql8.0.11 data directory migration

The default storage directory of mysql is /var/li...

JS+Canvas realizes dynamic clock effect

A dynamic clock demo based on Canvas is provided ...

Docker Machine in-depth explanation

Differences between Docker and Docker Machine Doc...

Detailed explanation of the process of docker packaging Python environment

The steps of docker packaging Python environment ...

Share 13 basic syntax of Typescript

Table of contents 1. What is Ts 2. Basic Grammar ...

Detailed graphic and text instructions for installing MySQL 5.7.20 on Mac OS

Installing MySQL 5.7 from TAR.GZ on Mac OS X Comp...

Solutions to the problem of table nesting and border merging

【question】 When the outer table and the inner tab...

MySQL 5.6.23 Installation and Configuration Environment Variables Tutorial

This article shares the installation and configur...

JavaScript anti-shake and throttling detailed explanation

Table of contents Debounce Throttle Summarize Deb...

MySQL 5.7.18 zip version installation tutorial

The mysql 5.7.18 zip version of MySQL is not like...

What to do if you forget your mysql password

Forgot your MySQL password twice? At first I did ...

Detailed explanation of JavaScript data types

Table of contents 1. Literals 1.1 Numeric literal...

25 Tools to Improve Website Usability and Conversion Rates

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