VUE使用SVG
1.安装依赖:
npm install svg-sprite-loader --save-dev
2.配置build文件夹中的webpack.base.conf.js,主要在两个地方添加代码,如下图所示
exclude: [resolve('src/icons')],
{ test: /\.svg$/, loader: 'svg-sprite-loader', include: [resolve('src/icons')], options: { symbolId: 'icon-[name]' } },
3.在src/下新建文件夹icons
svg文件夹:存放svg文件
gz-svg-icon.vue:svg显示组件
index.js入口:
gz-svg-icon.vue代码:
<template> <!-- <div> <h1>fdsf</h1> </div> --> <svg :class="svgClass" aria-hidden="true" v-on="$listeners"> <use :xlink:href="iconName" /> </svg> </template> <script> export default { name: "gz-svg-icon", 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>
index.js代码:
import Vue from 'vue' import GzSvgIcon from './gz-svg-icon.vue' // svg组件 // register globally Vue.component('gz-svg-icon', GzSvgIcon) // eslint-disable-next-line const req = require.context('./svg', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(requireContext) requireAll(req)
3.在main.js添加引用:
import './icons'
4.使用:
·1
慎于行,敏于思!GGGGGG