Introducing icons by implementing custom components based on Vue

Introducing icons by implementing custom components based on Vue

Preface

In project development, there are many ways to use icons. You can find suitable icons on iconfont and use them through http or directly download them. Here I share a way to introduce icons by implementing custom components.

Build the environment

Here we create a new project through @vue/cli 4.5.13, and we need to install the dependency svg-sprite-loader to process the corresponding svg icons for our convenience.

Installation: npm install --save-dev svg-sprite-loader

Configure vue.config.js

After installing svg-sprite-loader, create a new vue.config.js to configure dependencies:

// vue.config.js
const { resolve } = require('path')

module.exports = {
  chainWebpack(config) {
    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]'
      })
  }
}

Here are two configurations made through chainWebpack:

  • The first is to prevent the original other dependencies that process SVG from processing our custom icon files under src/icons
  • The custom icon file is processed by svg-sprite-loader. The settings in options indicate that the symbolId of the generated svg is the concatenation of the icon and the file name.

Create a new icon component

Create a new SvgIcon.vue file in the components directory:

<template>
  <i class="icon">
    <!-- aria-hidden, to help people with disabilities read (the device will skip this tag when reading the content to avoid confusion) -->
    <svg aria-hidden="true" :width="size" :height="size" :fill="fillColor">
      <use :xlink:href="iconName" rel="external nofollow" ></use>
    </svg>
  </i>
</template>

<script lang="ts">
import { PropType, toRefs } from 'vue'

export default {
  props: {
    size: {
      type: Number as PropType<number>,
      default: 14
    },
    fillColor: {
      type: String as PropType<string>,
      default: '#000'
    },
    iconName:
      type: String as PropType<string>,
      required: true
    }
  },
  setup(props: any) {
    const { size, fillColor, iconName: _iconName } = toRefs(props)
    const iconName = `#${_iconName.value}`

    return {
      size,
      fillColor,
      iconName
    }
  }
}
</script>

Then, create a new icons directory and a new index file to hang on the component and import the svg icon:

// index.ts
import SvgIcon from '@/components/SvgIcon.vue'
import { App } from 'vue'

export default (app: App) => {
  app.component('svg-icon', SvgIcon)
}

const ctx = require.context('./svg', false, /\.svg$/)
const requestAll = (ctx: __WebpackModuleApi.RequireContext) => ctx.keys().forEach(ctx)

requestAll(ctx)
//main.ts
import { createApp } from 'vue'
import App from './App.vue'
import installSvgIcon from '@/icons/index'

const app = createApp(App)

installSvgIcon(app)
app.mount('#app')

This file does two things:

  1. Mount the global component svg-icon by exporting a method;
  2. Use require.context to automatically import icon files in the svg directory.

Using Components

First, we need to store the SVG icon file in the icons/svg directory (find the one you need on iconfont);

Then, you can use it elsewhere:

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <svg-icon icon-name="icon-dashboard"></svg-icon>
  <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
</template>

Directly introduce it through the component svg-icon, and then pass in icon-name. The value of icon-name is composed of icon concatenated with the svg file name.

Summarize

This custom way of introducing SVG icons is quite convenient. When you want to add an icon, you can do it in a few steps:

  1. Download the svg file directly and put it in the corresponding directory;
  2. Then import it through the svg-icon component.

However, it is not very convenient to modify the style through CSS.

This concludes the article on how to introduce icons based on Vue’s custom components. For more information about Vue’s custom icon components, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use custom icon in Vue

<<:  Solution to mysql server 5.5 connection failure

>>:  How to expand the disk partition for centos system

Recommend

A brief analysis of the use of the HTML webpack plugin

Using the html-webpack-plugin plug-in to start th...

VUE implements timeline playback component

This article example shares the specific code of ...

HTML dynamically loads css styles and js scripts example

1. Dynamically loading scripts As the demand for ...

How to create a web wireframe using Photoshop

This post introduces a set of free Photoshop wire...

Detailed explanation of jQuery's copy object

<!DOCTYPE html> <html lang="en"...

Solution to using html2canvas to process Dom elements with Baidu map into images

Problem 1: Baidu Map uses tiled images (the map i...

In-depth explanation of the locking mechanism in MySQL InnoDB

Written in front A database is essentially a shar...

A brief discussion on the solution to excessive data in ElementUI el-select

Table of contents 1. Scenario Description 2. Solu...

Install multiple versions of PHP for Nginx on Linux

When we install and configure the server LNPM env...

Some tips on speeding up the development of WeChat mini-programs

1. Create a page using app.json According to our ...

JavaScript imitates Jingdong magnifying glass special effects

This article shares the specific code of JavaScri...

Linux system dual network card binding configuration implementation

System version [root@ ~]# cat /etc/redhat-release...

Usage instructions for the docker create command

The docker create command can create a container ...

A Deeper Look at SQL Injection

1. What is SQL injection? Sql injection is an att...