1. Directory structure

2. How does vuecli3 introduce SVG

  • 1, SvgIcon. Vue
<template> <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" /> <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners"> <use :xlink:href="iconName" /> </svg> </template> <script> function isExternal(path) { return /^(https? :|mailto:|tel:)/.test(path) } export default { name: 'SvgIcon', props: { iconClass: { type: String, required: true, }, className: { type: String, default: '', }, }, computed: { isExternal() { return isExternal(this.iconClass) }, iconName() { return `#icon-${this.iconClass}` }, svgClass() { if (this.className) { return 'svg-icon ' + this.className } else { return 'svg-icon' } }, styleExternalIcon() { return { mask: `url(${this.iconClass}) no-repeat 50% 50%`, '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`, } }, }, } </script> <style scoped> .svg-icon { width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } .svg-external-icon { background-color: currentColor; mask-size: cover ! important; display: inline-block; } </style>Copy the code
  • 2, the index. Js
import Vue from 'vue'
import SvgIcon from './SvgIcon'

Vue.component('SvgIcon', SvgIcon)
const req = require.context('./svg'.false, /\.svg$/)
const requireAll = requireContext= > requireContext.keys().map(requireContext)
requireAll(req)
Copy the code
  • 3, the main js
import './svg'
Copy the code
  • 4,npm i -D svg-sprite-loader
  • 5, vue. Config. Js
const path = require('path')
function resolve(dir) {
  // The path may be different from your project
  return path.join(__dirname, dir)
}

module.exports = {
  publicPath: '/'.css: {
    loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtoviewport({
            viewportWidth: 375,}),],},},},chainWebpack: config= > {
    config.module.rule('svg').uses.clear()
    config.module
      .rule('svg1')
      .test(/\.svg$/)
      .use('svg-sprite')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end()
      .include.add(resolve('src/svg')) // Notice here
      .end()
  },
}
Copy the code

3. How do I color SVG

  • Fill =”#D1D1D1″ fill=”currentColor” fill=”#D1D1D1″
  • Fill =”currentColor” fill=” XXX”
  • 2. This allows you to control the color of SVG inside the outer style. Of course the size can also be controlled!
  • Use:
<svg-icon icon-class="xxx" class-name="yyy"></svg-icon>
Copy the code

Inside the loop

<svg-icon :icon-class="o.svg" :class-name="o.svgCls"></svg-icon>
Copy the code

4, the end!