欢迎光临散文网 会员登陆 & 注册

vue2中如何正确配置svg

2023-07-18 04:22 作者:千诺谦修  | 我要投稿

在弄好了vue3模板之后,开始弄vue2模板,然后就卡在了svg配置上。

不是svg没显示就是svg没颜色以及颜色不正常,摸索了许久才配置正常。

vue3用的是vite,而vue2用的是vuecli所以配置会不同,下面是配置步骤:

先安装svg-sprite-loader: yarn add svg-sprite-loader -D

(我vue2用的yarn,vue3用的pnpm,当然你用什么随便你)

目录assets下创建icons文件夹用于存放svg

components下创建SvgIcon文件夹,内创建index.vue作为全局svg组件:

<template>

  <div :style="{ width: width, height: height, display: 'inline-block' }">

    <svg :style="{ width: width, height: height }">

      <use :xlink:href="prefix + name" :fill="color"></use>

    </svg>

  </div>

</template>


<script>

export default {

  name: "svgIcon",

  props: {

    // xlink:href属性值的前缀

    prefix: {

      type: String,

      default: "#icon-",

    },

    //svg矢量图的名字

    name: {

      type: String,

      require: true,

    },

    //svg图标的颜色

    color: {

      type: String,

      default: "",

    },

    //svg宽度

    width: {

      type: String,

      default: "16px",

    },

    //svg高度

    height: {

      type: String,

      default: "16px",

    },

  },

};

</script>

完成后在此index.vue同级目录下创建svgicon.js

import Vue from "vue";

import SvgIcon from "@/components/SvgIcon/index.vue";

// 全局注册组件

Vue.component("svg-icon", SvgIcon);

// 定义一个加载目录的函数

const requireAll = (requireContext) =>

  requireContext.keys().map(requireContext);

/**

 * require.context是什么?

 * 一个webpack的api,通过执行require.context函数获取一个特定的上下文,

 * 主要用来实现自动化导入模块(遍历文件夹的文件,从中获取指定文件,自动导入模块)

 * 在前端工程中,一个文件夹中的模块需要频繁引用时可以使用该中方式一次性引入

 * 可以使用这个api,它会遍历文件夹中的指定文件,

 * 然后自动导入,使得不需要每次显式的调用import导入模块

 */

const req = require.context("@/assets/icons", false, /.svg$/);

// 加载目录下的所有 svg 文件

requireAll(req);

完成后在main.js中全局注册组件:

// svg

import "@/components/SvgIcon/svgicon";

完成后在vueconfigjs中进行配置:

const path = require("path");

const { defineConfig } = require("@vue/cli-service");

const resolve = (dir) => path.join(__dirname, dir);


module.exports = defineConfig({

... //此处省略部分无关代码

  chainWebpack(config) {

    config.module.rule("svg").exclude.add(resolve("./src/assets/icons")).end();

    config.module

      .rule("icons")

      .test(/\.svg$/)

      .include.add(resolve("./src/assets/icons"))

      .end()

      .use("svg-sprite-loader")

      .loader("svg-sprite-loader")

      .options({

        symbolId: "icon-[name]",

      })

      .end();

  },

});

那么配置就已经完成了,在任意vue文件中使用:

<svg-icon name="vue" width="40px" height="40px"></svg-icon>

其中name属性要传入assets的icons的svg文件名,不带后缀


blue archive 启动






vue2中如何正确配置svg的评论 (共 条)

分享到微博请遵守国家法律