vue3中封装svg组件,并且全局注册

本文介绍了如何在Vite项目中安装并配置SVG图标插件,包括在配置文件中导入插件、创建SVG组件、封装并全局注册组件,以及在main.ts中引入和使用这些组件的过程。
摘要由CSDN通过智能技术生成

1.下载插件

cnpm i vite-plugin-svg-icons -D

2.在vite.config.ts中配置svg

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'

import vue from '@vitejs/plugin-vue'

import vueJsx from '@vitejs/plugin-vue-jsx'

import path from 'path'

//引入svg此插件 cnpm i vite-plugin-svg-icons -D

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

// https://vitejs.dev/config/

export default defineConfig({

  plugins: [

    vue(),

    vueJsx(),

    createSvgIconsPlugin({

      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], //取svg的文件路径

      symbolId: 'icon-[dir]-[name]',

    }),

  ],

  resolve: {

    alias: {

      '@': fileURLToPath(new URL('./src', import.meta.url)),

    },

  },

})

3.封装svg组件

<template>

  <!-- svg 结合use 使用 -->

  <svg :style="{ width, height }">

    <use :xlink:href="prefix + name" :fill="color"></use>

  </svg>

</template>

<script setup lang="ts">

//接收父组件传递过来的参数

defineProps({

  // xlink:href 属性值前缀

  prefix: {

    type: String,

    default: '#icon-',

  },

  // //接收父组件传递的名字

  name: {

    type: String,

    default: '',

  },

  //接收父组件传递的颜色

  color: {

    type: String,

    default: '',

  },

  //接收父组件传递的图标的宽度

  width: {

    type: String,

    default: '16px',

  },

  //接收父组件传递的图标的高度

  height: {

    type: String,

    default: '16px',

  },

})

</script>

4.全局注册组件 (在components下新建文件index.ts)

//引入全局组件

import SvgIcon from './SvgIcon/index.vue'

//我这里使用的ui 框架时arco-vue //根据实际取使用

//全局映入aroc-vue icon 

import ArcoVueIcon from '@arco-design/web-vue/es/icon'

//全局对象

const allGloabComponent = { SvgIcon }

// 暴露全局组件

export default {

  install(app: any) {

    //循环注入

    Object.keys(allGloabComponent).forEach((item) => {

      app.component(item, allGloabComponent[item])

    })

    //将element icon 注册全局

    for (const [key, component] of Object.entries(ArcoVueIcon)) {

      app.component(key, component)

    }

  },

}

5.在main.ts中引入

//引入自定义全局组件

import globalComponents from '@/components'

app.use(globalComponents)

6.使用

    <SvgIcon name="phone" color="red" width="50px" height="50px" />

//name 是你svg的名称

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值