vue-cli项目中使用SVG图片来作为图标

创建公共的vue-icon组件

// components/Icon-svg
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
 
<script>
export default {
  name: "SvgIcon",
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ""
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return "svg-icon " + this.className;
      } else {
        return "svg-icon";
      }
    }
  }
};
</script>
 
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

使用svg-sprite-loader插件来转换

svg-sprite-loader是webpack插件
1、安装
npm install svg-sprite-loader --save-dev
2、配置webpack
因为对于svg类型,webpack默认有一个loader 中也处理了 svg 文件,会和我们想要的效果冲突
使用 webpack 的 exclude 和 include ,让svg-sprite-loader只处理你指定文件夹下面的 svg,url-loaer只处理除此文件夹之外的所以 svg
在webpack.base.conf.js文件中修改配置

{
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      // 这段加入处理我们的svg方式和文件夹地址
      {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')], // 这里排除掉我们放置svg图标的文件夹地址
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      }

自动引入svg并自动转换

使用到 webpack 的 require.context
在src目录下,新建一个SvgIcon的文件夹,里面的代码如下:

// @/SvgIcon/index.js
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
 
<script>
export default {
  name: "SvgIcon",
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ""
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return "svg-icon " + this.className;
      } else {
        return "svg-icon";
      }
    }
  }
};
</script>
 
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

最后在main.js中引入

// main.js
// 引入icon组件
import '@/icons'
原创文章 103 获赞 128 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42991509/article/details/103145895