在项目中经常会用到svg图标,伴随着hover效果这样的需求,百度上一大堆人都在说修改fill
属性就能实现,但结果都是毫无效果。来看看我是怎么修改的。本教程含如何在vue中引入svg和修改svg颜色,如果想直接看如何修改svg颜色请看最下边。
首先在vue中引入svg图标
vue中引入svg图标
// index.js
import Vue from "vue";
import WbIcon from "@/components/icon/WbIcon.vue"; // svg component
/* register globally */
Vue.component("wb-icon", WbIcon);
const req = require.context("./svg", false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
// @/components/icon/WbIcon.vue
<template>
<svg class="wb-icon svg" aria-hidden="true" v-on="$listeners">
<use :href="iconName" />
</svg>
</template>
<script>
export default {
name: "WbIcon",
data() {
return {};
},
props: {
icon: {
type: String,
default: ""
}
},
computed: {
iconName() {
return `#icon-${this.icon}`;
}
}
};
</script>
<style lang="scss" scoped>
.wb-icon.svg {
width: 1em;
height: 1em;
fill: currentColor;
overflow: hidden;
vertical-align: middle;
}
</style>
然后在mian.js 注册
import Vue from "vue";
import "@/assets/icons"; // svg 存放在这个目录下。
new Vue({
router,
render: h => h(App)
}).$mount("#app");
组件中使用
<wb-icon icon="portal-simulation-rain"></wb-icon>
svg组成
svg 颜色绘制通常都是用fill
来实现。
svg样例
<?xml version="1.0" encoding="UTF-8"?>
<svg width="18px" height="18px" viewBox="0 0 18 18" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="页面-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="编组-9">
<rect id="矩形" fill="currentColor" opacity="0" x="0" y="0" width="18" height="18"></rect>
<g id="删除" transform="translate(1.285714, 1.285714)" fill="currentColor" fill-rule="nonzero">
<path d="M13.413643" id="形状"></path>
</g>
</g>
</g>
</svg>
修改
看上边的fill
属性是个none
,这样修改是方便咱们前端后期通过color
来修改。注意哦,这个只适用于单色svg图标。后边的fill
属性都要修改为fill=currentColor
。一定是都要才会有效果哦!
css
.icon:hover {
color: "#f20"
}
svg颜色才会随着css color 一起修改哦