美文网首页
svg-icon组件使用

svg-icon组件使用

作者: 小米和豆豆 | 来源:发表于2021-09-27 13:26 被阅读0次
  1. npm i svg-sprite-loader -D 或者yarn add svg-sprite-loader -D
  1. 新增svg-icon组件
<template>
  <svg class="svg-icon"
       aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>
<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    }
  }
}
</script>
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
  1. 在 该文件夹中创建 plugin.js 文件。在assets下创建svg文件夹存放svg图标
import SvgIcon from "./index";

const componentPlugin = {
    install: function (vue, options) {
        if (
            options &&
            options.imports &&
            Array.isArray(options.imports) &&
            options.imports.length > 0
        ) {
            // 按需引入图标
            const { imports } = options;
            imports.forEach((name) => {
                require(`@/assets/svg/${name}.svg`);
            });
        } else {
            // 全量引入图标
            const ctx = require.context("@/assets/svg", false, /\.svg$/);
            ctx.keys().forEach(path => {
                const temp = path.match(/\.\/([A-Za-z0-9\-_]+)\.svg$/);
                if (!temp) return;
                const name = temp[1];
                require(`@/assets/svg/${name}.svg`);
            });
        }
        vue.component(SvgIcon.name, SvgIcon);
    }
};
export default componentPlugin;
  1. 在 main.js 中导入插件
import plugin from "./components/SvgIcon/plugin";
Vue.use(plugin,{imports:[]});
  1. 修改 vue.config.js
const path = require("path");
const resolve = dir => path.join(__dirname, dir);
module.exports = {
  chainWebpack: config => {
    const svgRule = config.module.rule("svg");
    //webpack5 的配置有点区别  解开注释
    //svgRule.delete('type')
    //svgRule.delete('generator');

    svgRule.uses.clear();
    svgRule.exclude.add(/node_modules/);
    svgRule
      .test(/\.svg$/)
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      }).end();
  }
};

相关文章

网友评论

      本文标题:svg-icon组件使用

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