nuxt3批量引入svg文件
nuxt3引入svg的方法和viet的差不多,只是细节上有些不同
同样是两步,引入svg组件和引入svg文件
第一步:引入svg组件
在components文件夹下创建SvgIcon.vue组件
<template> <svg class="svgclass" aria-hidden="true"> <use :xlink:href="symbolId" :fill="color" /> </svg> </template> <script setup>
import { defineProps, computed } from 'vue'
const props = defineProps({ prefix: { type: String, default: 'icon', }, name: { type: String, required: true, }, color: { type: String, default: '#333', }, }) const symbolId = computed(() => `#${props.prefix}-${props.name}`) </script> <style scoped lang='scss' > .svgclass { width: 1em; height: 1em; overflow: hidden; vertical-align: top; } </style>
在plugins文件夹下创建svgicon.client.ts引入
import svgIcon from '@/components/SvgIcon.vue' export default defineNuxtPlugin(nuxtApp => { nuxtApp.vueApp.component('svg-icon', svgIcon) })
第二步:引入svg文件
这里用到vite-plugin-svg-icons这个库,官方介绍:https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md
npm i vite-plugin-svg-icons -D
在nuxt.config.ts里面添加以下内容,注意文件夹路径要填对
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' import path from 'path' export default defineNuxtConfig({ ... vite: { plugins: [ createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), 'assets/svg')] }) ], } ... })
在plugins文件夹下的svgicon.client.ts文件中添加注入脚本
import 'virtual:svg-icons-register'
如果使用 Typescript
,你可以在tsconfig.json
内添加
// tsconfig.json { "compilerOptions": { "types": ["vite-plugin-svg-icons/client"] } }
第三步:使用
传入svg文件夹中的名称就可以了
效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)