Vue3使用icon的两种方式

Vue3 中使用Icon的方式,fontAwesome 简单好用,但有时候缺少想要的icon。采用svg的方式,想要什么,直接下载,然后使用,种类更加的全,基本上没有不符合需求的icon,但是没有fontAwesome 相对的容易轻松,每次都要下载对应的图片。

 

1. 使用svg

a 下载需要使用的SVG图片,保存至 src/icons文件夹

b 安装依赖 fs 和svg的loader

命令:npm install svg-sprite-loader

命令:npm install --save fs

c 创建模板文件 index.vue

模板文件代码

<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 全局注册 main.js

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

e 创建导入处理函数 在plugins中创建 svgBulider.js

代码

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 修改配置文件,将svgBulider导入到配置文件

修改vite.config.js

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

export default defineConfig({
plugins: [
    vue(),
    //调用对应的函数 进行 svg 处理
    svgBuilder('./src/icons/')//对应的文件夹,否则无法找到
  ]
})

g 使用SVG

核心部分

<svg-icon name="questionmark" />//name 取你的svg图片

 

2. 使用fontAwesome

a npm 安装依赖

$ 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 全局注册

  //按需导入
  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 { 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 使用

  //按需导入的使用
    <font-awesome-icon  icon="address-book" class="fa-spin fa-lg"/>
  //全局导入的使用
    <font-awesome-icon  :icon="['fas','address-book']" />

 

3 来源

来源 fontAwesome https://www.jb51.net/article/228944.htm

来源 svg https://www.jb51.net/article/228948.htm

 

4 总结

确定对应的技术栈和版本,按照步骤,就没什么问题。

关于Vue3使用icon的两种方式的文章就介绍至此,更多相关Vue3使用icon内容请搜索编程宝库以前的文章,希望以后支持编程宝库

前端小伙伴们都知道Font Awesome图标库,它具有丰富的常用图标,笔者开发时也经常使用,省却了自己到处找图标的困扰,当然阿里的iconfont也不错,不过它比较杂乱,找的图标有时候不是配 ...