vue2.6中svg的使用,可改变icon颜色(svg-sprite-loader)
2020-07-14 05:51
567 查看
由于项目需要,要在项目中使用设计师给的 icon 图标,可改变 icon 的颜色。
插件:svg-sprite-loader
版本:@vue/cli 4.3.1
使用:
-
npm install -D svg-sprite-loader
-
在 src/components/ 下创建 SvgIcon 组件
配置SvgIcon.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>
-
新建目录,将 svg 文件放到该目录下 src/icons/svg
-
配置 index.js , 注册组件,全局使用
import Vue from 'vue' import SvgIcon from '@/components/SvgIcon'// svg组件 // register globally Vue.component('svg-icon', SvgIcon) const requireAll = requireContext => requireContext.keys().map(requireContext) /** * require.context(directory,useSubdirectories,regExp) * require.context():需要一次性的引入某个文件夹下的所有文件 形参: directory:需要引入文件的目录 useSubdirectories:是否查找该目录下的子级目录 regExp:匹配引入文件的正则表达式 */ const req = require.context('./svg', false, /\.svg$/) requireAll(req)
-
在 main.js 中引入
import '@/icons'
-
在和src同级的目录下创建vue.config.js并配置如下代码,
vue-cli3 开始有默认的 svg和images 的loader ,需要手动排除const path = require('path') function resolve (dir) { return path.join(__dirname, './', dir) } module.exports = { chainWebpack: config => { const svgRule = config.module.rule('svg') // 找到svg-loader svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后 svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录 svgRule // 添加svg新的loader处理 .test(/\.svg$/) .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) // 修改images loader 添加svg处理 const imagesRule = config.module.rule('images') imagesRule.exclude.add(resolve('src/icons')) config.module .rule('images') .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/) } }
-
在组件中使用,stroke属性可以修改icon的颜色
<svg-icon :icon-class=svg文件的名字如setting" :stroke="'#4bc8c8'"></svg-icon>
参考链接
https://www.cnblogs.com/cat-eol/p/11784125.html
https://www.jb51.net/article/149452.htm
相关文章推荐
- 使用Vue(svg-sprite-loader、vue2-svg-icon)重构svg管网监控图
- VUE-cli3使用 svg-sprite-loader
- SVG Sprite 使用Symbol元素制作ICON
- react中SVG的使用(改变大小颜色) + REM的缩放大小(sketch复制代码)
- 使用svg-sprite-loader 遇到的问题
- 如何在VUE项目里使用阿里巴巴 iconfont 图标库里的彩色图标(svg图标)
- 使用svg-sprite-loader 遇到的问题
- 如何在vue循环列表中实现点赞改变icon和字体颜色,不可取消点赞
- background-image使用svg如何改变颜色
- 【转】进度条的使用(设置值,改变颜色)
- Sprite setBlendFunc 使用颜色混合:加算,减算
- VC 使用OnCtlColor函数来改变控件颜色(引用)
- iOS开发笔记--使用blend改变图片颜色
- 使用SVG中的Symbol元素制作Icon(链接地址)
- Android点击控件改变颜色的两种方法——onTouchLisener()和xml资源文件selector的使用
- 杂记之使用代码动态的改变文本、按钮的颜色
- iOS中使用blend改变图片颜色
- svg中改变class调用的线条颜色
- 非owner drawn使用CImageList改变Icon模式CListCtrl的Item宽度和高度
- Android LinearLayout使用selector改变交互时背景颜色