@vue/cli 4.x.x中引入svg loader

1.vue.config.js

loader处理

module.exports = defineConfig({
    chainWebpack: config => {
      //排除icons目录中svg文件处理
      config.module.rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
      //设置svg-sprite-loader处理icons目录中的svg
      config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader("svg-sprite-loader")
      .options({symbolId:'icon-[name]'})
      .end()
    }

2.新建index.js

// 自动导入的方法
export function importAllSvg() {
    const importAll = (requireContext) =>
      requireContext.keys().forEach(requireContext)
  
    try {
      // 导入src/icons/svg下的所有以.svg结尾的文件
      importAll(require.context('@/icons', false, /\.svg$/))
    } catch (error) {
      console.log(error)
    }
  }

3.写一个svg的公共组件

<template>
    <svg class="svg-icon" aria-hidden="true" v-bind="$attrs" :class="className">
        <use :xlink:href="iconName" />
    </svg>
</template>

<script setup>
import { toRefs, computed, defineProps } from "vue";

const props = defineProps({
    icon: {
        type: String,
        required: true,
    },
    svgClass: {
        type: String,
        default: "",
    },
});
const iconName = computed(() => `#icon-${props.icon}`);
const className = computed(() => {
    if (props.svgClass === undefined) {
        return "";
    }
    return props.svgClass;
});
</script>

<style lang="less" scoped>
.svg-icon {
    width: 1em;
    height: 1em;
    overflow: hidden;
    vertical-align: -0.15em;
    fill: currentColor;
}
</style>

4.将index.js引入main,js

import {importAllSvg} from "@/index.js"
importAllSvg()

5.组件中使用

// jince是在icon中定义的svg名字
<template>
    <div class="home">
        <svgIcon icon="jince"></svgIcon>
    </div>
</template>

<script setup>
import svgIcon from "@/components/svgIcon/svgIcon.vue";
</script>

<style scoped lang="less">
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值