vue3 SVG 图标配置-阿里巴巴矢量库,封装全局组件

在开发项目的时候经常会用到svg矢量图,而且我们使用 SVG 以后,页面上加载的不再是图片资源。

这对页面性能来说是个很大的提升,而且我们 SVG 文件比 img 要小的很多,放在项目中几乎不占用资源。

下载 SVG 图标经常用到 iconfont-阿里巴巴矢量图标

1 安装SVG依赖插件及配置

pnpm install vite-plugin-svg-icons -D

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

import 'virtual:svg-icons-register'

使用

<script setup>
console.log(import.meta.env)
</script>

<template>
  <h1>APP</h1>
  <!-- svg 外层容器 -->
  <svg width="30px" height="30px">
    <!-- 如果不生效,从新启动 -->
    <!-- #icon-固定的,需要加上后面图片的名称(src/assets/icons/phone.svg) -->
    <use href="#icon-phone" fill="#007dff"></use>
  </svg>
</template>
<style scoped></style>

将 svg 封装为全局组件

因为项目很多模块需要使用图标,因此把它封装为全局组件。

在src/components目录下创建一个SvgIcon组件:代表如下

<template>
  <div>
    <svg :style="{ width: width, height: height }">
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup >
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></style>

在src文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件。

// 引入项目中全部的全局组件
import SvgIcon from './SvgIcon/index.vue';
import type { App, Component } from 'vue';
// 全局对象 allGlobalComponents 里面有属性 SvgIcon 等,作为键;而值是一个个 Component 自身组件对象
const allGlobalComponents: { [name: string]: Component } = { SvgIcon };

// 对外暴露插件对象
export default {
  //使用install方法
  install(app: App) {
    // 遍历对象,将对象中的组件注册到vue中,成为全局组件
    Object.keys(allGlobalComponents).forEach((key) => {
      // 注册组件
      app.component(key, allGlobalComponents[key]);
    }
    )
  }
};

在main.js

在入口文件引入src/index.ts文件,通过app.use方法安装自定义插件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前端小云儿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值