vite配置 vue3中怎么使用svg图标

18 篇文章 0 订阅

svg图片在项目中使用的非常广泛,如何在vue3 + vite 中使用svg图标。

vite-plugin-svg-icons

  • 预加载 在项目运行时就生成所有图标,只需操作一次 dom
  • 高性能 内置缓存,仅当文件被修改时才会重新生成
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

再vite.config.ts里面配置插件

导入

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

然后再plugins中配置

 plugins: [vue(),createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
    iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    }),],

然后再main.ts中引入

import 'virtual:svg-icons-register'

再svgIcon.vue中

<template>
    <svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
      <use :xlink:href="symbolId" rel="external nofollow"  :fill="props.color" />
    </svg>
  </template>
  
  <script setup lang="ts">
  import { computed } from 'vue'
  const props = defineProps({
    prefix: {
      type: String,
      default: 'icon'
    },
    name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: '#333'
    },
    size: {
      type: String,
      default: '1em'
    }
  })
  const symbolId = computed(() => `#${props.prefix}-${props.name}`)
  </script>

再main.ts中全局注册

import svgIcon from "@/components/SvgIcon/index.vue";
app.component('svg-icon', svgIcon)

 页面中使用

<template>
    <svg-icon v-if="props.icon" :name="props.icon" />
    <span v-if="props.title" slot='title'>{{ props.title }}</span>
</template>

<script setup lang="ts">
const props = defineProps({
    icon: {
        type: String,
        default: ''
    },
    title: {
        type: String,
        default: ''
    }
})
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值