
在考虑了将矢量图标从图标字体迁移到内联 SVG 的 原因 之后,我在 Vue.js 中找到了一个用 SVG 替换图标字体的解决方案,同时仍能保持使用图标字体的灵活性和易用性——能够使用 CSS 轻松改变图标的大小、颜色以及其它属性。
一种流行的方法是使用 v-html 指令和 npm 模块 html-loader 来将 SVG 导入到我们的 Vue 模板中,并在 Vue 的生命周期函数 mounted() 中修改渲染的 <svg> 元素。CSS 样式可以直接应用到 <svg> 元素或者是其父元素上,并且这些能够组成一个可复用的组件。
创建 Svg-icon 组件
让我们创建 Svg-icon.vue 组件文件,并在里面接收三个 prop 变量。
<script>
function recursivelyRemoveFill(el) {
if (!el) {
return;
}
el.removeAttribute('fill');
[].forEach.call(el.children, child => {
recursivelyRemoveFill(child);
});
}
export default {
name: 'svg-icon',
props: {
icon: {
type: String,
default: null
},
hasFill: {
type: Boolean,
default: false
},
growByHeight: {
type: Boolean,
default: true
},
},
mounted() {
if (this.$el.firstElementChild.nodeName === 'svg') {
const svgElement = this.$el.firstElementChild;
const widthToHeight = (svgElement.clientWidth / svgElement.clientHeight).toFixed(2);
if (this.hasFill) {
// recursively remove all fill attribute of element and its nested children
recursivelyRemoveFill(svgElement);
}
// set width and height relative to font size
// if growByHeight is true, height set to 1em else width set to 1em and remaining is calculated based on widthToHeight ratio
if (this.growByHeight) {
svgElement.setAttribute('height', '1em');
svgElement.setAttribute('width', `${widthToHeight}em`);
} else {
svgElement.setAttribute('width', '1em');
svgElement.setAttribute('height', `${1 / widthToHeight}em`);
}
svgElement.classList.add('svg-class');
}
}
}
</script>
<template>
<div v-html="require(`html-loader!../assets/svg/${icon}.svg`)" class="svg-container"></div>
</template>
<style lang="scss" scoped>
.svg-container {
display: inline-flex;
}
.svg-class {
vertical-align: middle;
}
</style>另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。