Encapsulation and use of svg icons in projects

1.Installation

npm install vite-plugin-svg-icons -D

2. Configure in vite.config.ts

       ​ **All svg icons must be placed in assets/icons

// 引入svg
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
    }),
  ],、
})

3.Introduce in the entry file

// svg插件需要配置代码
import 'virtual:svg-icons-register'

4.Use

The svg icon generated by Alibaba icon is placed under assets/icons

<!-- svg:图标外层容器节点,内部需要use标签结合使用 -->
<svg>
    <!-- xlink:href 执行哪一个图标,属性值必须 #icon-图标名字 -->
    <!-- use标签使用fill属性设置图标颜色 -->
    <use xlink:href="#icon-phone" fill="yellow"></use>
 </svg>

Encapsulate an svg component

1: Local components

<template>
  <svg :style="{ width, height }">
    <use :xlink:href="prefix + name" :fill="color"></use>
  </svg>
</template>
<script setup lang="ts">

defineProps({
  // xlink:href属性前缀
  prefix: {
    type: String,
    default: '#icon-',
  },
  // 图标名字
  name: String,
  // 图标颜色
  color: {
    type: String,
    default: '',
  },
  // 图标宽度
  width: {
    type: String,
    default: '16px',
  },
  // 图标高度
  height: {
    type: String,
    default: '16px',
  },
})
</script>
<script scoped lang="scss"></script>

Quote

import SvgIcon from "@/components/SvgIcon/index.vue"
<svg-icon name="expand" color="pink" height="20px" width="20px"></svg-icon>

2. Global components

1. Create a new index.ts in the components folder, introduce all svg icon components into index.ts, and expose the entire file.

// 引入项目中全部的全局组件
import SvgIcon from './SvgIcon/index.vue'

// 全局对象
const allGloablComponent = { SvgIcon }
// 暴露插件对象
export default {
  install(app) {
    Object.keys(allGloablComponent).forEach((key) => {
      app.component(key, allGloablComponent[key])
    })
  },
}

2. Set global components in main.ts

// 引入自定义插件对象,注册整个项目全局组件
import gloablComponent from '@/components'
// 安装自定义插件
app.use(gloablComponent)

After performing the above operations, you can use the component directly in the project without introducing it.

Guess you like

Origin blog.csdn.net/weixin_50999303/article/details/134671538