終于給搞定了!下面來個總結(jié)吧:
1俯在、先在package.json中引入改含,再執(zhí)行安裝晃虫,應(yīng)注意是項目使用 vue init webpack vue-demo01?創(chuàng)建的而非 vue init webpack-simple vuedemo02荠商。
npm install svg-sprite-loader --save-dev
2寂恬、webpack.base.conf.js配置中 加入
{
? ? ? ? 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')],//排除該目錄? 其他規(guī)則中有svg 需要加入排除
? ? ? ? options: {
? ? ? ? ? limit: 10000,
? ? ? ? ? name: utils.assetsPath('img/[name].[hash:7].[ext]')
? ? ? ? }
? ? ? }
3、建立組件:src/components/SvgIcon/index.vue
<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: 1em;
? height: 1em;
? vertical-align: -0.15em;
? fill: currentColor;
? overflow: hidden;
}
</style>
4莱没、建立文件夾:src/icons/svg/ 放入*.svg文件初肉;src/icons/index.js?
index.js 的代碼如下:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
export default req
5、全局引入icons:src/main.js 加入代碼
import './icons' // icon
6饰躲、使用icon:list既是list.svg牙咏,再App.vue 中加入代碼
<svg-icon icon-class="list" class-name="disabled" />
7、運(yùn)行項目,就能看到您的圖標(biāo)了嘹裂!
npm run dev