Vue3使用icon的两种方式实例

2022-04-15 0 776
目录
  • 1. 使用svg
  • 2. 使用fontAwesome
  • 3  来源
  • 4 总结

技术栈和版本 Vite2 + Vue3 + fontAwesome5

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

1. 使用svg

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

Vue3使用icon的两种方式实例

b 安装依赖 fs 和svg的loader

命令:npm install svg-sprite-loader

命令:npm install --save fs

c 创建模板文件 index.vue

Vue3使用icon的两种方式实例

模板文件代码

<template>
    <svg :class="svgClass" v-bind = "$attrs">
        <use :xlink:href="iconName" rel="external nofollow" ></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

Vue3使用icon的两种方式实例

代码

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

Vue3使用icon的两种方式实例

核心部分

  <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']" />

Vue3使用icon的两种方式实例

3  来源

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

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

4 总结

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

到此这篇关于Vue3使用icon的两种方式的文章就介绍到这了,更多相关Vue3使用icon内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript Vue3使用icon的两种方式实例 https://www.niceym.com/19483.html