vue3+vite配置全局使用的svg组件

1.通过pnpm安装引入svg需要用的插件

pnpm i vite-plugin-svg-icons

2.在vite.config.ts中配置

export default defineConfig({
  plugins: [
  	//此处省略代码。。。
    //icon全局配置
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
    }),
    //此处省略代码。。。
  ],
})

3.封装icon全局组件

// component/SvgIcon/index.vue
<template>
  <!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
  <svg :style="{ width, height }">
      <!-- xlink:href执行用哪一个图标,属性值务必#icon-图标名字 -->
      <!-- use标签fill属性可以设置图标的颜色 -->
      <use :xlink:href="prefix + name" :fill="color"></use>
  </svg>
</template>

<script setup lang="ts">
//接受父组件传递过来的参数
defineProps({
  //xlink:href属性值前缀
  prefix: {
      type: String,
      default: '#icon-'
  },
  //提供使用的图标名字
  name: String,
  //接受父组件传递颜色
  color: {
      type: String,
      default: ''
  },
  //接受父组件传递过来的图标的宽度
  width: {
      type: String,
      default: '16px'
  },
  //接受父组件传递过来的图标的高度
  height: {
      type: String,
      default: '16px'
  }
})
</script>

<style scoped></style>

4.注册成全局组件

//component/index.ts
//引入项目中全部的全局组件
import SvgIcon from './SvgIcon/index.vue';
//全局对象
const allGloablComponent: any = { SvgIcon };
//对外暴露插件对象
export default {
    //务必叫做install方法
    install(app: any) {
        //注册项目全部的全局组件
        Object.keys(allGloablComponent).forEach(key => {
            //注册为全局组件
            app.component(key, allGloablComponent[key]);
        });
    }
}

5.在main.ts中配置

import { createApp } from 'vue'

//svg插件需要配置代码
import 'virtual:svg-icons-register'
//引入自定义插件对象:注册整个项目全局组件
import gloalComponent from '@/components'

const app = createApp(App)

//安装自定义插件
app.use(gloalComponent)
app.mount('#app')

6.去下载或复制svg图标在

/assets/icons/

7.使用

<svg-icon name="swtIcon" width="10px" height="10px"></svg-icon>
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值