vite-ts-vue3.0引入svg

2022-04-27  本文已影响0人  如果俞天阳会飞

使用vite-plugin-svg-icons插件

yarn add vite-plugin-svg-icons -D

vite.config.ts 中的配置插件

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

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

在 src/main.ts 内引入注册脚本

import 'virtual:svg-icons-register'

如何在组件使用

/src/components/SvgIcon.vue

<template>
  <svg aria-hidden="true" width="40px" height="40px">
    <use :xlink:href="symbolId" />
  </svg>
</template>

<template>
  <svg aria-hidden="true" width="40px" height="40px">
    <use :xlink:href="symbolId" fill="color"/>
  </svg>
</template>

<script lang="ts" setup>
import { computed } from 'vue';

interface IProps {
    /** svg 的图标的名称 */
    iconName: string,
    color: string,
}
const props = defineProps<IProps>();
const symbolId = computed(() => `#icon-${props.iconName}`);
</script>

使用

 <base-svg icon-name="loading" />
上一篇 下一篇

猜你喜欢

热点阅读