Vite-Vue3-TypeScript:010-封装svg
    		       		warning:
    		            这篇文章距离上次修改已过435天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue3项目中,我们可以通过创建一个自定义组件来封装SVG图标。这样可以在整个应用中复用SVG图标,并且可以通过props来动态调整SVG的一些属性,如颜色、大小等。
首先,在项目中创建一个新的.vue文件,例如SvgIcon.vue。
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
 
<script lang="ts">
import { defineComponent, PropType } from 'vue';
 
export default defineComponent({
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String as PropType<string>,
      required: true
    },
    className: {
      type: String as PropType<string>,
      default: ''
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className;
      } else {
        return 'svg-icon';
      }
    }
  }
});
</script>
 
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  overflow: hidden;
}
</style>然后,在components目录下创建一个index.ts文件,将SvgIcon.vue组件导入并注册为全局组件:
import SvgIcon from './SvgIcon.vue';
 
export default (app: any) => {
  app.component('SvgIcon', SvgIcon);
};最后,在main.ts文件中导入并使用这个注册函数:
import { createApp } from 'vue';
import App from './App.vue';
import setupComponents from './components'; // 导入组件注册函数
 
const app = createApp(App);
setupComponents(app); // 注册全局组件
 
app.mount('#app');现在,你可以在任何组件中使用<SvgIcon icon-class="example" />来引用SVG图标了。其中icon-class是你在SVG sprite 文件中定义的图标的ID,不包括#前缀。
评论已关闭