主要是介绍下SVG图标组件在Vue2.x中的配置流程
首先,假设你有一个图标为:calculator.svg
最后想要通过下图的这种方式来使用它:
遵循以下步骤便可以实现:
1. 先编写一个SvgIcon组件
<template> <svg class="svg-icon" aria-hidden="true"> <use :xlink:href="iconName" /> </svg> </template> <script> export default { name: 'SvgIcon', props: { icon: { type: String, required: true, }, }, computed: { iconName() { return '#icon-' + this.icon; }, }, }; </script> <style> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
2. 添加一个icon-requirer.js来完成本地svg图标集的引入
const svgResources = require.context('./assets/svg/icons', false, /\.svg$/); svgResources.keys().forEach(svg => { svgResources(svg); });
3. 将icon-requirer.js引入main.js,并全局注册SvgIcon组件
import Vue from 'vue'; import App from './App.vue'; import SvgIcon from './components/SvgIcon.vue'; import './icon-requirer'; Vue.component(SvgIcon.name, SvgIcon); Vue.config.productionTip = false; new Vue({ render: h => h(App), }).$mount('#app');
4. 下载 svg-sprite-loader 和 svgo.loader 两个webpack loader
前者是一个用于创建 svg 雪碧图的 Webpack 加载器,它会把你引入的 svg 塞到一个个 symbol 中,合成一个大的 svg 插入到文档内;
后者可以帮助我们手动删除svg文件代码中的fill属性;
npm i -D svg-sprite-loader svgo-loader
5. 更改vue.config.js中的配置
const path = require('path') const { defineConfig } = require('@vue/cli-service') const resolve = dir => path.join(__dirname, dir); module.exports = defineConfig({ transpileDependencies: true, chainWebpack(config) { config.module.rule('svg') .exclude .add(resolve('./src/assets/svg/icons')) .end() config.module .rule('icons') .test(/\.svg$/) .include.add(resolve('./src/assets/svg/icons')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]', }) .end() .use('svgo-loader') .loader('svgo-loader') .options({ plugins: [ { name: 'removeAttrs', params: { attrs: 'fill', }, } ], }) .end(); } });
如上配置后,就可以了
最后,贴出package.json的依赖内容(Vue Cli是5.x的版本)
"dependencies": { "core-js": "^3.8.3", "vue": "^2.6.14" }, "devDependencies": { "@babel/core": "^7.12.16", "@babel/eslint-parser": "^7.12.16", "@vue/cli-plugin-babel": "~5.0.0", "@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-service": "~5.0.0", "eslint": "^7.32.0", "eslint-plugin-vue": "^8.0.3", "svg-sprite-loader": "^6.0.11", "svgo-loader": "^3.0.3", "vue-template-compiler": "^2.6.14" },
标签:vue,Cli,svg,loader,Vue,SvgIcon,icon From: https://www.cnblogs.com/fanqshun/p/16926663.html