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

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>

猜你喜欢

转载自blog.csdn.net/qq_27449993/article/details/127221528