Vue3封装svg组件

封装svg 组件

在components 新建组件

目录:components/SvgIcon/index.vue

封装:

<script setup>
import { computed } from 'vue'
const props = defineProps({
  iconClass: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  }
})
const iconName = computed(() => {
  return `#icon-${props.iconClass}`
})
const svgClass = computed(() => {
  if (props.className) {
    return 'svg-icon ' + props.className
  } else {
    return 'svg-icon'
  }
})
</script>
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

注册组件:

目录:/src/icons/index.js

import SvgIcon from '@/components/SvgIcon/index.vue'
export default {
  install(app) {
    const components = { SvgIcon }
    Object.keys(components).forEach((key) => {
      app.component(key, components[key])
    })
  }
}

安装插件

插件1:vite-plugin-svg-icons

npm install vite-plugin-svg-icons 

插件2:fast-glob

npm install fast-glob

注册全局组件

在main.js 文件引入相关文件

import 'virtual:svg-icons-register'
import SvgIcon from '@/icons/index.js'
app.use(SvgIcon)

配置打包文件

在vite.config.js

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      // 指定要缓存.svg文件的文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
      symbolId: 'icon-[dir]-[name]'
    })
  ],
})

相关推荐

  1. Vue3封装svg

    2024-04-29 04:32:03       14 阅读
  2. vue3.0-monaco封装

    2024-04-29 04:32:03       13 阅读
  3. Vue3项目filter.js封装

    2024-04-29 04:32:03       36 阅读
  4. vue3 封装一个通用echarts

    2024-04-29 04:32:03       40 阅读
  5. vite+vue3项目中svg图标组件封装

    2024-04-29 04:32:03       20 阅读
  6. 如何在 vue 项目中创建 svg

    2024-04-29 04:32:03       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-29 04:32:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-29 04:32:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-29 04:32:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-29 04:32:03       18 阅读

热门阅读

  1. Springboot 使用hutool国密算法

    2024-04-29 04:32:03       19 阅读
  2. 联合国官方统计的十大基本原则是什么

    2024-04-29 04:32:03       15 阅读
  3. PCIE与上位机调试流程

    2024-04-29 04:32:03       37 阅读
  4. 杆塔倾斜测量原理

    2024-04-29 04:32:03       27 阅读
  5. TypeScript 学习笔记

    2024-04-29 04:32:03       40 阅读
  6. 线程池问题

    2024-04-29 04:32:03       11 阅读
  7. 事务与锁机制

    2024-04-29 04:32:03       12 阅读