本文共 3246 字,大约阅读时间需要 10 分钟。
npm install svg-sprite-loader --save-dev
{ test: /\.svg$/, loader: 'svg-sprite-loader', include: [resolve('src/icons')], options: { symbolId: 'icon-[name]'//去掉svg这个图片加载不出来 } }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', //这个不处理svg图片,因为我们独立拆开让svg-sprite-loader来处理了 exclude: [resolve('src/icons')], options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } },
<template> <svg :class="svgClass" aria-hidden="true"> <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: 10rem; height: 10rem; vertical-align: -0.15em; fill: currentColor; overflow: hidden; }</style>
import Vue from 'vue'import SvgIcon from '@/components/SvgIcon'// svg组件// register globallyVue.component('svg-icon', SvgIcon)const req = require.context('./svg', false, /\.svg$/)const requireAll = requireContext => requireContext.keys().map(requireContext)requireAll(req)
import Vue from 'vue'import App from './App'import router from './router'//引入整个icons,import './icons'Vue.config.productionTip = false/* eslint-disable no-new */new Vue({ el: '#app', router, components: { App }, template: '<App/>'})
<template> <div class="hello"> <h1>{ { msg }}</h1> <h2>Essential Links</h2> <svg-icon icon-class="smile" size="10"></svg-icon> </div></template><script>export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }}</script><!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>h1, h2 { font-weight: normal;}ul { list-style-type: none; padding: 0;}li { display: inline-block; margin: 0 10px;}a { color: #42b983;}</style>
npm install vue2-svg-icon --save-dev
// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from './App'import router from './router'//import './icons/index.js'//引入vue2-svg-icon并且注册组件import Icon from 'vue2-svg-icon/Icon'Vue.component('icon',Icon);Vue.config.productionTip = false/* eslint-disable no-new */new Vue({ el: '#app', router, components: { App }, template: '<App/>'})
转载地址:http://bakh.baihongyu.com/