Vue实战之从零搭建Vite2+Vue3全家桶(三)

2,053 阅读1分钟

前言

闲暇时间写写文章,能写多少写多少,主要是用来总结完善一下自己的技术栈,查漏补缺。 上一篇完善了http请求工具的使用,本篇主要介绍icon图标管理插件的使用。

上一篇传送门

Vue实战之从零搭建Vite2+Vue3全家桶(二)

icon图标管理

这里采用\textrm\color{red}{ vite-plugin-svg-icons}插件来对svg图标进行管理

vite-plugin-svg-icons特征

  • 预加载,在项目运行时就生成所有图标,只需要操作一次dom
  • 高性能 内置缓存,仅当文件被修改时才会重新生成

安装vite-plugin-svg-icons

  # 安装要求
  # node version: >=12.0.0
  # vite version: >=2.0.0

  npm i vite-plugin-svg-icons -d

修改vite.config.js

import viteSvgIcons from 'vite-plugin-svg-icons'
plugins: [
  vue(),
  viteSvgIcons({
    // 配置路劲在你的src里的svg存放文件
    iconDirs: [path.resolve(process.cwd(), 'src/icons')],
    symbolId: 'icon-[name]'
  })
]

封装SvgIcon组件

创建svgIcon公共组件

src/components目录下新建SvgIcon目录,SvgIcon目录下新建index.vue

  <template>
    <svg aria-hidden="true" class="svg-icon">
      <use :xlink:href="symbolId" :fill="color" />
    </svg>
  </template>

  <script>
  import { defineComponent, computed } from 'vue'

  export default defineComponent({
    name: 'SvgIcon',
    props: {
      prefix: {
        type: String,
        default: 'icon'
      },
      name: {
        type: String,
        required: true
      },
      color: {
        type: String,
        default: 'white'
      }
    },
    setup(props) {
      const symbolId = computed(() => `#${props.prefix}-${props.name}`)
      return { symbolId }
    }
  })
  </script>
  <style scoped>
  .svg-icon {
    width: 1em;
    height: 1em;
    fill: currentColor;
    vertical-align: middle;
  }
  </style>

icons目录结构

# src/icons

- password.svg
- username.svg
- ...

修改main.js

 import 'virtual:svg-icons-register' 
 import SvgIcon from '@/components/SvgIcon/index.vue' 

 const app = createApp(App)
 app.component('svg-icon', SvgIcon)

vue组件中使用svgIcon

<template>
...
 <svg-icon name="password"  />
...
</template>

往期传送门

Vue实战之从零搭建Vite2+Vue3全家桶(二)

Vue实战之从零搭建Vite2+Vue3全家桶(一)

基于Vue的架构设计