vue使用svg
svg-sprite-loader 的插件,用来根据导入的 svg 文件自动生成 symbol 标签并插入 html,接下来就可以在模版中方便地使用 svg-sprite 技术了。
使用 svg-sprite 的好处
如果不知道 svg-sprite 是什么,可以参考大神张鑫旭的文章:未来必热:SVG Sprite技术介绍
- 页面代码清爽
- 可使用 ID 随处重复调用
- 每个 SVG 图标都可以更改大小颜色
使用方法
1.安装依赖
npm install svg-sprite-loader –save-dev
2.在src/components下新建文件夹及文件SvgIcon/index.vue 组件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <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 scoped> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
|
3.在src/assets/icons下新建index.js文件, index.js文件内容如下

1 2 3 4 5 6 7 8 9
| 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)
|
4.在src/plugins/element.js 引入src/assets/icons下index.js文件 (在把element.js引入到main.js中)

1 2 3 4 5 6 7
| import Vue from 'vue' import Element from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import '../assets/icons/index.js' import axios from './axios' Vue.use(Element) Vue.use(axios)
|
5.在vue.config.js文件中配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const path = require('path');
function resolve(dir) { return path.join(__dirname, dir) } chainWebpack(config) { config.plugins.delete('preload') config.plugins.delete('prefetch') config.module .rule('svg') .exclude.add(resolve('src/assets/icons')) .end() config.module .rule('icons') .test(/\.svg$/) .include.add(resolve('src/assets/icons')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() }
|
6.项目中使用
在src/assets/icons/svg下新建user.svg
1
| <svg width="130" height="130" xmlns="http://www.w3.org/2000/svg"><path d="M63.444 64.996c20.633 0 37.359-14.308 37.359-31.953 0-17.649-16.726-31.952-37.359-31.952-20.631 0-37.36 14.303-37.358 31.952 0 17.645 16.727 31.953 37.359 31.953zM80.57 75.65H49.434c-26.652 0-48.26 18.477-48.26 41.27v2.664c0 9.316 21.608 9.325 48.26 9.325H80.57c26.649 0 48.256-.344 48.256-9.325v-2.663c0-22.794-21.605-41.271-48.256-41.271z" stroke="#979797"/></svg>
|
