【nuxt3】项目中使用svg 7步带你了解

 1.创建svg图标存放文件夹

在nuxt3项目中 项目目录如下图所示 我们需要在项目根目录下的assets目录创建svg,然后我们的svg图标就放在这里面,当然你也可以自己定义svg图标放置的位置,调整路径配置即可

2.创建SvgIcon.vue组件,包装SVG

在项目根目录下的components目录里创建SvgIcon.vue, 这个.vue文件就是我们自定义的图标组件, 代码如下

<template>
  <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  name: {
    type: String,
    required: true
  },
  color: {
    type: String,
    default: ''
  }
})

const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => {
  if (props.name) {
    return `svg-icon icon-${props.name}`
  }
  return 'svg-icon'
})
</script>

<style lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

 3.创建svgicon.client.ts

在plugins文件夹下创建svgicon.client.ts引入

import svgIcon from '@/components/SvgIcon.vue'
export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.vueApp.component('svg-icon', svgIcon)
})

4.安装 vite-plugin-svg-icons

 官方介绍:vite-plugin-svg-icons/README.zh_CN.md at main · vbenjs/vite-plugin-svg-icons · GitHub

npm i vite-plugin-svg-icons -D

5.设置nuxt.config.ts 

在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')]
            })
        ],
    }
...
})

6.svgicon.client.ts文件中添加注入脚本

import 'virtual:svg-icons-register'

如果是用TS 可以在tsconfig.json内添加 

复制代码
// tsconfig.json
{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}

 7.最后 可以在页面中使用啦

 如下

<svg-icon name="home"></svg-icon>

 

注:最后 如果使用之后页面还是没显示 请检查一下第五步的步骤对不对

制作不易!看到最后 希望你能 点赞!!!关注!!

猜你喜欢

转载自blog.csdn.net/weixin_49014702/article/details/128414398