下载的svg图标颜色更改不了时,将svg的后缀名svg改为html,找到里面的fill中的固有色的fill="currentColor"就可以了。
使用svg代替图片,封装svg组件,实现颜色大小变化。
1.首先下载插件
npm i vite-plugin-svg-icons //图标插件
npm i fast-glob -D //报错的话要再下载一个这个解决报错问题
2.配置vite.config.ts
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [vue(),
//插件在plugins中写入
createSvgIconsPlugin({
// 指定要缓存.svg文件的文件夹位置,src/assets/icons/svg为svg图片的存放位置
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
],
server: {
},
})
3.封装icon组件
在component中写入组件
<template>
<svg class="svg-icon" aria-hidden="true" >
<use :xlink:href="iconNames" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue'
let props = defineProps({
iconName: {//svg图片名称
type: String,
required: true
},
})
const iconNames = computed(() => `#icon-${props.iconName}`)
</script>
<style scope>
/* .sub-el-icon,
.nav-icon {
display: inline-block;
font-size: 15px;
margin-right: 12px;
position: relative;
} */
.svg-icon {
/* width: 1em;
height: 1em;
position: relative; */
fill: currentColor;
/* vertical-align: -2px; */
}
</style>
4.注册全局组件
当然也可以直接在页面中引入,局部引入,这里采用的是全局引入,后期直接在页面中使用就可
在main.ts中引入:
import svgIcon from './components/iconImage/index.vue'
import "virtual:svg-icons-register";
app.component('SvgIcon', svgIcon)
5.组件中使用示例
<template>
<div>
<div class="left">
//直接在页面中引入svgIcon就可以了,那个iconName是svg图标的名称
<svgIcon iconName="11" style="width:100px;height:100px;"></svgIcon>
</div>
</div>
</template>
6.存在的问题
哦,对了还有一种会出现的情况就是color的颜色不会更改的问题,
这种情况下可以将svg图片转成html的格式,将fill中写死的值变更为currentColor就好了