components目录下新建svg目录
svg目录下新建app.ts
import { defineNuxtModule, createResolver, addComponent } from '@nuxt/kit'
export default defineNuxtModule({
setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url)
addComponent({
name: 'AppSvg',
global: true,
filePath: resolve('./index.vue')
})
}
})
svg目录下新建index.vue
<template>
<span class="app-svg" v-html="icon" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
/**
* 定义组件属性
*/
const props = withDefaults(
defineProps<{
name?: string,
filled?: boolean
}>(), {
filled: false
}
)
const icon = ref<string | Record<string, any>>('')
try {
const iconsImport = import.meta.glob('/static/svg/**/**.svg', { query: '?raw', eager: false })
const rawIcon = await iconsImport[`/static/svg/${props.name}.svg`]()
if (typeof rawIcon === 'object' && 'default' in rawIcon! && typeof rawIcon.default === 'string') {
icon.value = rawIcon.default
} else {
console.error('[app-svg] 无法提取有效的 SVG 数据')
}
} catch {
console.error(`[app-svg] svg '${props.name}' 在 'static/svg' 目录中不存在`)
}
</script>
<style>
.app-svg {
display: flex;
}
</style>
根目录nuxt.config.ts
modules: ['~/components/svg/app'],
使用方法
<AppSvg name="Svg名" />