Install SVG – Sprite – loader
npm install svg-sprite-loader --save
Copy the code
Packaging components
The directory structure
.
│ App.vue
│ main.js├─ ├─ ├─ bass exercises.vue│ ├ ─ the router │ index.js│ ├ ─ store │ actions.js
│ index.js
│ mutations.js│ ├─svgIcons │ index.js│ │ ├ ─ └ │ certification.svg
│
Copy the code
Show the magistrate the code
cd src/components/SvgIcon/index.vue
Copy the code
<template> <svg :class='svgClass' aria-hidden="true" v-on="$listeners"> <use :xlink:href='iconName' /> </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> .svg-icon{ width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code
cd src/svgIcons/index.js
Copy the code
import Vue from "vue"
import SvgIcon from "@/components/SvgIcon"
Vue.component("svg-icon",SvgIcon);
const req = require.context("./svg".false./\.svg$/)
const requireAll = requireContext= > requireContext.keys().map(requireContext)
requireAll(req)
Copy the code
src/svgIcons/svg/xxx.svg
Copy the code
cd src/main/js
Copy the code
import './svgIcons'
Copy the code
Modify the WebPack configuration
-
Increase the loader
{ test: /\.svg$/, loader: 'svg-sprite-loader'.include: [resolve('src/svgIcons')].options: { symbolId: 'icon-[name]'}}Copy the code
. Note that a tip of SVG should be excluded when urL-loader introduces it. Note that a tip of SVG should be excluded when URL-loader introduces SVG.Copy the code
{
test: /\.(png|jpe? g|gif|svg)(\? . *)? $/,
loader: 'url-loader'.exclude: [resolve('src/svgIcons')].options: {
limit: 10000.name: utils.assetsPath('img/[name].[hash:7].[ext]')}}Copy the code
How to use it in business code? Trick:
<svg-icon icon-class='xxx' class="" style=""></svg-icon>
Copy the code
A recruit dead, after finishing work, remember (°▽°) Blue ✿