vue3中把封装svg图标为全局组件

在vue3中我们使用svg图标是下面这样子的

vue 复制代码
    <svg style="width:30px;height:30px;">
      <use xlink:href="#icon-phone" fill="red"></use>
    </svg>

第次使用图标都要写这么多重复的代码,很不方便,所以,如果我们把它封装成全局的组件, 就可以很方便的使用了

首先我们要看 svg 图标使用时 变化的部分有哪几个

所以我们新建一个组件 SvgIcon

SvgIcon.vue 的代码如下

.vue 复制代码
<script setup lang="ts" name="SvgIcon">
  let props = defineProps({
    iconname: {
      type: String,
      default: '',
    },
    width: {
      type: [Number,String],
      default: 16,
    },
    height: {
      type: [Number,String],
      default: 16,
    },
    color:{
      type:String,
      default:'#666'
    }
  })
</script>

<template>
  <div class="wrapper">
    <svg :style="{width:width+'px',height:height+'px'}">
      <use :xlink:href="`#icon-${iconname}`" :fill="color"/>
    </svg>
  </div>
</template>

<style scoped>

</style>

在页面中调用就可以了


以上是在单组件中调用, 每次使用 都要引入才可以使用,我们现在把它设置成全局组件,就不需要 每个调用的地方都要 import SvgIcon from "@/components/SvgIcon.vue";

我们只需要在 main.ts中注册自定义的组件为全局组件就可以了

相关推荐
FungLeo7 小时前
成为全栈·React 管理后台篇·总复盘:从“接口能调通”到“后台值得使用”
前端·react.js·前端框架·项目复盘·成为全栈
Csvn8 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_8 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt8 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
JavaGuide9 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel9 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
莪_幻尘11 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm
风骏时光牛马11 小时前
AI模型综合能力评测:性能、指令遵循与多场景实测对比
前端
Frag0ut11 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm
hiahiahia12311 小时前
实现完整 Tool Dispatcher
开发语言·前端