1.首先安裝javascript
npm install --save-dev svg-sprite-loader
2. 在webpack.base.conf.js中手動添加vue
module: { { 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')], options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, }
3. 在src/components下新增一個文件夾 SvgIcon/index.vue,代碼以下:java
<template> <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName"></use> </svg> </template> <script> export default { name: 'svg-icon', props: { iconClass: { type: String, required: true }, className: { type: String } }, 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>
4. 在src下新增文件夾icons/svg存放svg圖
icons/index.js代碼以下: webpack
import Vue from 'vue' import SvgIcon from '@/components/SvgIcon'// svg組件 // register globally Vue.component('svg-icon', SvgIcon) const requireAll = requireContext => requireContext.keys().map(requireContext) const req = require.context('./svg', false, /\.svg$/) requireAll(req)
5. 在main.js中引入:web
import '@/icons' // icon
6. 從新npm
npm run dev
7. vue的文件中就能夠用啦!! 界面使用 如:svg
<svg-icon icon-class="userName" /> //userName是svg圖的命名