Home  >  Article  >  Web Front-end  >  How to use svg method in vue3+vite2

How to use svg method in vue3+vite2

WBOY
WBOYforward
2023-05-11 17:55:061653browse

1. Install vite-plugin-svg-icons

You also need to install fast-glob related dependencies here, otherwise vite will report a Cannot find module 'fast-glob’ error when running npm run dev

npm i fast-glob@3.x -D
npm i vite-plugin-svg-icons@2.x -D

2. Create a new component index.vue under src/components/svgIcon

<template>
  <svg aria-hidden="true" class="svg-icon">
    <use :xlink:href="symbolId" rel="external nofollow"  :fill="color" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from &#39;vue&#39;;

const props = defineProps({
  prefix: {type: String,default: &#39;icon&#39;,},
  iconClass: {type: String,required: true,},
  color: {type: String,default: &#39;&#39;}
})

const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  overflow: hidden;
  fill: currentColor;
}
</style>

3. Add settings in tsconfig.json

types to specify the modules that need to be included , only the declaration files of the modules listed here will be loaded. It is not necessary to add it. When I tested the two demos, one required it and the other did not. If you have any problems, you can try adding

{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}

4. Configuration plug-in in vite.config.ts

import { resolve } from &#39;path&#39;
import { createSvgIconsPlugin } from &#39;vite-plugin-svg-icons&#39;

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [resolve(process.cwd(), &#39;src/assets/imgs/svg&#39;)],
      // 指定symbolId格式
      symbolId: &#39;icon-[dir]-[name]&#39;,
    })
  ]
})

5. Register the component globally in main.ts

import { createApp } from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import router from &#39;@/router&#39;
import { store, key } from &#39;@/store&#39;

const app = createApp(App)

import &#39;virtual:svg-icons-register&#39; // 引入注册脚本
import SvgIcon from &#39;@/components/svgIcon/index.vue&#39; // 引入组件
app.component(&#39;svg-icon&#39;, SvgIcon)

app.use(router).use(store, key).mount(&#39;#app&#39;)

6. Use

<template>
  <svg-icon icon-class="category"></svg-icon>
  <svg-icon icon-class="accountant" ></svg-icon>
</template>

in the page 7. File directory structure and its effect display

How to use svg method in vue3+vite2

The above is the detailed content of How to use svg method in vue3+vite2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete