在Vue3的项目中,当我们想要在页面中显示svg图片,我们可以将 svg 图片的文件路径传递给 img
标签的 src
属性来显示,文件中一长串的文件路径,这种方式不太优雅。
另一种方式就是通过 vite-plugin-svg-icons
插件渲染,也就是本文主讲的重点。
使用步骤
-
安装。
npm install vite-plugin-svg-icons -D
-
配置。在vite的配置文件中添加插件配置:
// vite.config.js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' export default defineConfig({ plugins: [ vue(), createSvgIconsPlugin({ // 指定需要缓存的svg图标文件目录 iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], // 指定symbolId格式 symbolId: 'icon-[dir]-[name]' }) ] })
-
在项目中创建步骤2中指定的svg文件夹目录 ( 示例指定
src/assets/icons
),并将 svg 图标放入该目录。 -
在项目的入口文件中注册 svg-icon
// main.js // ...... import 'virtual:svg-icons-register' // ......
-
创建 SvgIcon 组件。
<!-- components/SvgIcon/index.vue --> <template> <svg aria-hidden="true"> <use :xlink:href="`#${prefix}-${name}`" /> </svg> </template> <script> import { defineComponent } from 'vue' export default defineComponent({ props: { prefix: { type: String, default: 'icon' }, name: { type: String, required: true, }, } }) </script>
-
使用。例如,在
src/assets/icons
目录下有一个logo.svg
图标,页面中使用的时候,我们只需要传入文件名(不包括文件后缀)给 SvgIcon 便可以加载该图片。<template> <div> <SvgIcon name="logo" /> </div> </template> <!-- 略... -->
除了定义 SvgIcon 组件的方式,还有另一种灵活取用方式。步骤1、2、3同上。
-
使用 svg。通过
name
属性来指定要使用的图标名称,然后将器作为普通的 vue 组件使用。这种方式不需要引入virtual:svg-icons-register
<template> <div> <Icon name="logo" /> </div> </template> <script> import { defineComponent } from 'vue' import Icon from 'vite-plugin-svg-icons/Icon' export default defineComponent({ components: { Icon } }) </script>