美文网首页
vue3+vite中实现全局的自定义svg效果

vue3+vite中实现全局的自定义svg效果

作者: 匆匆那年_海 | 来源:发表于2023-01-05 19:27 被阅读0次

    1.安装相应的插件

    cnpm i fast-glob vite-plugin-svg-icons -S
    

    2.vite.config.js中新增下面内容

    import path from 'path'
    import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    // https://vitejs.dev/config/
    export default defineConfig({
        plugins: [
            vue(),
            createSvgIconsPlugin({
                // 指定需要缓存的图标文件夹
                iconDirs: [path.resolve(process.cwd(), 'src/assets/img/svg')],
                // 指定symbolId格式
                symbolId: '[name]'
            })
        ],
    });
    

    3.main.js中配置全局组件

    // 全局icon配置
    import 'virtual:svg-icons-register'
    // 引入组件
    import svgIcon from '@/components/svg.vue'
    const app = createApp(App);
    app.component('svgIcon', svgIcon)
    
    svg.vue
    <template>
        <svg :class="svgClass" aria-hidden="true">
            <use :xlink:href="iconName" />
        </svg>
    </template>
    
    <script setup>
    import { computed } from "vue";
    const props = defineProps({
        iconClass: { type: String, required: true },
        className: { type: String, default: '' }
    })
    const iconName = computed(() => `#${props.iconClass}`);
    const svgClass = computed(() => {
        if (props.className) {
            return 'svg-icon ' + props.className
        } else {
            return 'svg-icon'
        }
    });
    
    </script>
    
    <style scoped>
    .svg-icon {
        margin-right: 12px;
        fill: currentColor;
        overflow: hidden;
    }
    </style>
    

    4.在页面上使用,注意home是svg的名称,注意下载下来的svg文件必须打开删除fill="none"和fill="#xxxxxx",否则无法修改颜色

    <svgIcon iconClass="home" className="img1" />
    .img1 {
          width: 16px;
          height: 14px;
          color: #165DFF;
    }
    

    5.效果

    效果.png

    原文作者:匆匆那年_海,博客主页:https://www.jianshu.com/u/910c0667c515
    95后前端汉子,爱编程、优秀、聪明、理性、沉稳、智慧的程序猿一枚。

    相关文章

      网友评论

          本文标题:vue3+vite中实现全局的自定义svg效果

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