vue3自动引入 svg

下载sv svg 图片下载地址 (来自阿里巴巴的免费项目 iconfont)

项目演示
github地址 vue-ant-design
gitee地址 vue-ant-design 项目地址
项目4个分支 ant-design ant-dessign-electron element-plus element-plus-electron

1 安装 svg 依赖

npm install --save-dev svg-sprite-loader

2 新建文件

svg--
	 --index.js 
	 --svg.vue
	 --icon文件夹

在这里插入图片描述

3 配置信息

index.js
//下面这个是导入svgIcon/svg下的所有svg文件
const requireAll = (requireContext) => requireContext.keys().map(requireContext)
const req = require.context('./icon', false, /\.svg$/)
/*
 第一个参数是:'./svg' => 需要检索的目录,
 第二个参数是:false => 是否检索子目录,
 第三个参数是: /\.svg$/ => 匹配文件的正则
*/
requireAll(req)
svg.vue

<template>
    <svg class="svg-icon " :class="className" :style="size?`width:${size}px;height:${size}px;`:''" aria-hidden="true">
      <use :xlink:href="svgName" />
    </svg>
  </template>
  
  <script setup>
    import {
    
     ref,computed } from 'vue';
  // 声明组件要触发的事件
  const emits = defineEmits(['increase']);
  // 声明接收参数
  const props = defineProps({
    
    
    svg: String,
    class: String,
    size: Number,
  });
  const svgName=computed(()=>`#icon-${
      
      props.svg}` )
  const className=computed(()=>props.class)
  const size=computed(()=>props.size)

  </script>
  
  <style scoped>
  .svg-icon {
    
    
    width: 16px;
    height: 16px;
    vertical-align: -0.25em;
    fill: currentColor;
    overflow: hidden;
  }
  </style>

4 配置vue.fonfig.js

module.exports = {
    
    
  chainWebpack(config) {
    
    
      const svgRule = config.module.rule('svg') // 找到svg-loader
      svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
      svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
      svgRule // 添加svg新的loader处理
        .test(/\.svg$/)
        .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
    
    
          symbolId: 'icon-[name]',
        })
      // 修改images loader 添加svg处理
      const imagesRule = config.module.rule('images')
      imagesRule.exclude.add(resolve('src/common/svg'))
      config.module
        .rule('images')
        .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
        }
        }

在这里插入图片描述

main.js 组成svg 文件

import   "@/common/svg/index"

页面使用

  <svgView :svg="value.icon" ></svgView> 
    
 import svgView from "@/common/svg/svg.vue"
 
   export default {
    
    
        components:{
    
    
            svgView
        },
        

猜你喜欢

转载自blog.csdn.net/qq_44795810/article/details/129326207
SVG