美文网首页vue
Vite 2 + Vue 3 实现 svg 图标

Vite 2 + Vue 3 实现 svg 图标

作者: AizawaSayo | 来源:发表于2021-08-29 01:53 被阅读0次

    迁移项目发现 vue 2 + webpack 的方法到这不好使了,于是另起炉灶。记录📝一下这个适用 Vite 2 + Vue 3 的解决方案。

    1. 先安装插件:

    vite-plugin-svg-iconsGitHub文档

    npm i vite-plugin-svg-icons -D
    // 或
    yarn add vite-plugin-svg-icons -D
    

    2. 配置插件

    📃vite.config.js / vite.config.ts

    import viteSvgIcons from 'vite-plugin-svg-icons';
    import path from 'path'; // ts如果报错 npm i @types/node -D
    
    export default () => {
      return {
        plugins: [
          viteSvgIcons({
            // 配置你存放 svg 图标的目录
            iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
            // 定义 symbolId 格式
            symbolId: 'icon-[dir]-[name]',
          }),
        ],
      };
    };
    
    我的 svg 文件路径

    3. SvgIcon 组件实现

    📃src/components/SvgIcon.vue

    <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: '#889aa4',
        },
      },
      setup(props) {
        return {
          iconName: computed(() => `#icon-${props.iconClass}`),
          svgClass: computed(() => {
            if (props.className) {
              return `svg-icon ${props.className}`
            }
            return 'svg-icon'
          }),
        }
      },
    })
    </script>
    
    <style scope>
    .svg-icon {
      width: 1em;
      height: 1em;
      fill: currentColor;
      vertical-align: middle;
    }
    </style>
    

    4. 在📃 main.js / main.ts 引入插件注册脚本

    import 'vite-plugin-svg-icons/register';
    

    5. 在📃 main.js / main.ts 全局注册 svg 组件

    (单独在用到的组件引入也可)

    import svgIcon from './components/SvgIcon.vue'
    app.component('svg-icon', svgIcon)
    

    6. 使用方法:

    <template>
      <div>
         <svg-icon icon-class="password" />
      </div>
    </template>
    
    <script>
      import { defineComponent, computed } from 'vue';
      export default defineComponent({
        name: 'Login',
      });
    </script>
    

    转载自:vite2.0-vue3如何快速实现svg图标

    相关文章

      网友评论

        本文标题:Vite 2 + Vue 3 实现 svg 图标

        本文链接:https://www.haomeiwen.com/subject/jyqwiltx.html