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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值