Vue封装全局SVG组件

1.SVG图标配置

1.安装插件

npm install vite-plugin-svg-icons -D

2.Vite.config.ts中配置

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}

3.main.ts中导入

//SVG插件必须的配置
import 'virtual:svg-icons-register'

4.组件内使用

1.下载svg代码

阿里巴巴图标库或者其他图标库下载SVG代码,复制到对应的文件中

2.SVG使用
<template>
  <div>
    <!-- svg:图标的外层节点,内部需要于use标签结合使用 -->
    <svg style="width: 30px; height: 30px;">
      <!-- xlink:href执行用的图标,属性务必是#icon-图标名字 -->
      <!-- use标签的fill属性为图标的颜色填充 -->
      <use xlink:href="#icon-base" fill="blue"></use>
    </svg>
  </div>
</template>

<script setup lang="ts"></script>

<style scoped lang="scss"></style>

2.SVG组件封装

1.创建组件文件

2.封装组件 

<template>
  <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-'
  },
  //svg矢量图的名字
  name: String,
  //svg图标的颜色
  color: {
    type: String,
    default: ''
  },
  //svg宽度
  width: {
    type: String,
    default: '16px'
  },
  //svg高度
  height: {
    type: String,
    default: '16px'
  }
})
</script>

<style scoped lang="scss"></style>

3.在其他组件使用

<template>
  <div>
    <SvgIcon name="base" width="30px" height="30px" color="blue"></SvgIcon>
  </div>
</template>

<script setup lang="ts">
import SvgIcon from '@/components/Svg/index.vue'
</script>

<style scoped lang="scss"></style>

3.SVG组件注册为全局组件

1.创建文件

2.注册全局组件

//引入全局组件
import SvgIcon from './SvgIcon/index.vue';
import type { App, Component } from 'vue';
//全局对象
const components: { [name: string]: Component } = { SvgIcon };
//对外暴露插件对象
export default {
    //insatll方法
    install(app: App) {
        //注册项目为全局组件(可注册多个)
        Object.keys(components).forEach((key: string) => {
            //注册全局组件
            app.component(key, components[key]);
        })
    }
}

3.引入到main.ts

import gloablComponent from './components/index';
app.use(gloablComponent);

4.组件中使用

<template>
  <div>
    <SvgIcon name="base" width="30px" height="30px" color="blue"></SvgIcon>
  </div>
</template>

<script setup lang="ts"></script>

<style scoped lang="scss"></style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卷小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值