超级悠悠
高性能程序定制、UI定制
546612

访问

0

评论

19

动态

2029

运行

来过
设计群: 70888820
位置: luzhou·sichuan

- 今日签到 -

今日暂无签到

首页破碎代码Nuxt3 自定义SVG图标(不依赖任何第三方插件)

Nuxt3 自定义SVG图标(不依赖任何第三方插件)

评论 0/访问 876/分类: 破碎代码/发布时间:

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名" />

收藏

点赞

打赏