記錄一下svgicon元件的使用

一尘子!發表於2024-12-03

總是忘記若依中怎麼引用的svgicon,記錄一下

yarn add vite-plugin-svg-icons
--------
vite.config.ts

plugins: [vue(),createSvgIconsPlugin({
      // 指定要快取的圖示資料夾
      iconDirs: [resolve(process.cwd(), "./src/assets/icons/svg")],
      // 執行icon name的格式
      symbolId: "icon-[name]",
 })],
--------
main.ts
// svg圖示
import 'virtual:svg-icons-register'
import SvgIcon from '/@/components/SvgIcon/index.vue'
import elementIcons from '/@/components/SvgIcon/svgicon.js'
app.use(elementIcons)
app.component('svg-icon', SvgIcon)
--------
svgicon資料夾

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>

<script>
import { computed, defineComponent } from 'vue';

export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: ''
    },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`
        }
        return 'svg-icon'
      })
    }
  }
})
</script>

<style scope lang="scss">
.sub-el-icon,
.nav-icon {
  display: inline-block;
  font-size: 15px;
  margin-right: 12px;
  position: relative;
}

.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

--------
import * as components from '@element-plus/icons-vue'

export default {
  install: (app) => {
        for (const key in components) {
            const componentConfig = components[key];
            app.component(componentConfig.name, componentConfig);
        }
    },
};
--------
 <svg-icon  icon-class="404" />

相關文章