vue3系列:构建 SvgIcon 组件

效果图

 1.  组件编写 components/SvgIcon.vue

<script setup>
import { computed } from 'vue'

const props = defineProps({
  name: {
    type: String,
    required: true
  },
  className: String,
  color: String,
  width: String,
  height: String
})

const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => {
  let className = props.className ? `icon-${props.className}` : '';
  return ['svg-icon', className]
})

</script>
<template>
  <!-- aria-hidden: 让这个元素对浏览器隐藏 -->
  <svg :class="svgClass" :style="{ color, width, height }" aria-hidden="true" v-bind="$attrs">
    <use :xlink:href="iconName" />
  </svg>
</template>

<style scoped>
.svg-icon {
  width: 1.3em;
  height: 1.3em;
  vertical-align: -0.3em;
  fill: currentColor;
  overflow: hidden;
}
</style>

2. 创建文件夹 assets/svg 文件夹,存放 .svg 文件

 3. 安装依赖

3.1 安装 svg 依赖 vite-plugin-svg-icons

3.2 配套安装 fast-glob

yarn add vite-plugin-svg-icons
yarn add fast-glob
// or
npm install vite-plugin-svg-icons
npm install fast-glob

4. vite.config.js 编写

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

// https://vitejs.dev/config/
import { resolve } from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"),
    },
  },
  plugins: [
    vue(),
    createSvgIconsPlugin({
      // 指定缓存文件
      iconDirs: [resolve(process.cwd(), "src/assets/svg")],
      // 指定symbolId格式
      symbolId: "icon-[dir]-[name]",
    }),
  ],
});

5. main.js 编写

import { createApp } from "vue";
import App from "./App.vue";
// svg 组件
import SvgIcon from "@/components/SvgIcon.vue";
import "virtual:svg-icons-register";

const app = createApp(App);
app.component("svg-icon", SvgIcon).mount("#app");

6. 使用

<script setup>
</script>

<template>
  <div id="app">
    <!--  name: 必填 svg 的文件名
          className: 选填 class 类名
          color: 选填 颜色
          width: 选填 宽
          height: 选填 高  -->
    <svg-icon name="phone" color="red" width="50" height="50"></svg-icon>
  </div>
</template>

<style scoped>
</style>

7. 特别提示:如果 color 属性无效,需删除 .svg 文件里 fill="" 属性

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yqcoder

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

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

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

打赏作者

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

抵扣说明:

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

余额充值