• vite vue引入svg图标及封装 (轻松上手)


    svg特征

    • Preloading所有图标都是在项目运行时生成的,只需要操作一次dom即可。
    • 高性能内置缓存,仅在文件被修改时才会重新生成。

    一、如何使用

    1.安装vite-plugin-svg-icons插件

    node version: >=12.0.0

    vite version: >=2.0.0

    1. yarn add vite-plugin-svg-icons -D
    2. # or
    3. npm i vite-plugin-svg-icons -D
    4. # or
    5. pnpm install vite-plugin-svg-icons -D

    2.使用插件

    vite.config.ts

    1. import { VantResolver } from 'unplugin-vue-components/resolvers'
    2. +import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    3. +import path from 'path'
    4. // https://vitejs.dev/config/
    5. export default defineConfig({
    6. plugins: [
    7. vue(),
    8. Components({
    9. dts: false,
    10. resolvers: [VantResolver({ importStyle: false })]
    11. }),
    12. + createSvgIconsPlugin({
    13. + // 指定图标文件夹,绝对路径(NODE代码)
    14. + iconDirs: [path.resolve(process.cwd(), 'src/icons')]
    15. + })
    16. ],

    目录结构

     

    3. 全局引入

    main.ts

    import 'virtual:svg-icons-register'

    4. 使用

    1. <svg aria-hidden="true">  
    2.    
    3.  <use href="#icon-login-eye-off" />
    4. svg>

    二、封装

    components/CpIcon.vue

    1. <template>
    2. <svg aria-hidden="true" class="cp-icon">
    3. <use :href="`#icon-${name}`" />
    4. svg>
    5. template>
    6. <style lang="scss" scoped>
    7. .cp-icon {
    8. // 和字体一样大
    9. width: 1em;
    10. height: 1em;
    11. }
    12. style>

    提供使用时提示 类型 types/components.d.ts 

    1. import CpIcon from '@/components/CpIcon.vue'
    2. declare module 'vue' {
    3. interface GlobalComponents {
    4. CpIcon: typeof CpIcon
    5. }
    6. }

    提示:有些图标可以根据 style 中 color 的值来设置颜色,图标是否有这个功能取决于 UI 做图片时否开启

    使用: 

     "login-eye-on">
    

  • 相关阅读:
    Docker 学习总结(78)—— Docker Rootless 让你的容器更安全
    五年数据库专家,带你深入高性能 MySQL 架构系统,不要等到面试再追悔莫及
    java8 .stream().map().collect() 的用法
    1. Unified Structure Generation for Universal Information Extraction 阅读笔记
    AI推介-大语言模型LLMs论文速览(arXiv方向):2024.06.05-2024.06.10
    flask第一个应用
    SpringBoot+Vue实现前后端分离的个性化课程推荐系统
    Swift函数调用方式浅析
    C#中Math类中的常用函数
    react+ts实战之 @reduxjs/toolkit
  • 原文地址:https://blog.csdn.net/m0_46846526/article/details/127765708