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

Detailed usage of Vue timer

This article example shares the specific code of ...

How to gracefully and safely shut down the MySQL process

Preface This article analyzes the process of shut...

Sample code for implementing Alipay sandbox payment with Vue+SpringBoot

First, download a series of things from the Alipa...

How to run multiple MySQL instances in Windows

Preface In Windows, you can start multiple MySQL ...

Mysql SQL statement operation to add or modify primary key

Add table fields alter table table1 add transacto...

JS Easy to understand Function and Constructor

Table of contents 1. Overview 1.1 Creating a func...

Steps to build the vite+vue3+element-plus project

Use vite to build a vue3 project You can quickly ...

Linux RabbitMQ cluster construction process diagram

1. Overall steps At the beginning, we introduced ...

Detailed explanation of simple snow effect example using JS

Table of contents Preface Main implementation cod...

Vue complete code to implement single sign-on control

Here is a Vue single sign-on demo for your refere...

MySQL learning tutorial clustered index

Clustering is actually relative to the InnoDB dat...

How to dynamically add a volume to a running Docker container

Someone asked me before whether it is possible to...