vue3引入使用svg图标

vue3使用svg图标

安装

// 通过命令安装2个插件
npm i vite-plugin-svg-icons -D
npm i fast-glob -D

在vue.config.js中配置

//vue.config.js
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

存放的路径地址:src/assets/svg/.

封装svg组件

<template>
    <svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
      <use :xlink:href="symbolId" :fill="props.color" />
    </svg>
  </template>
  
  <script setup>
  import { computed } from 'vue'
  const props = defineProps({
    prefix: {
      type: String,
      default: 'icon'
    },
    name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: '#333'
    },
    size: {
      type: String,
      default: '1em'
    }
  })
  
  const symbolId = computed(() => `#${props.prefix}-${props.name}`)
  </script>
</style>

在main.js中引入使用

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router/index'

import naive from './plugins/naive'

//引入
import 'virtual:svg-icons-register'
import SvgIcon from './components/SvgIcon.vue'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.use(naive)

//引入
app.component('svg-icon', SvgIcon)

app.mount('#app')

使用方式:

<template>
        <SvgIcon  name="icon1" size="24"  />
</template>

<script setup>
import SvgIcon from "@/components/SvgIcon.vue";
</script>

<style scoped lang="scss">
</style>
posted @ 2023-12-29 14:17  ProsperousEnding  阅读(916)  评论(0编辑  收藏  举报