手摸手,带你优雅的使用 icon
这是花裤衩在掘金上发布的关于这个优雅的使用icon的过程
这是关于如何自己封装一个组件上传npm库
久在vue后台管理系统混迹的童鞋应该知道花裤衩
的吧,我用了他的vue-admin-template
模板,顺便学习了一下大佬的代码,里面有一个使用svg-icon
的组件,认真看了下,因为我一般用的都是阿里爸爸iconfont
官方的那种使用方式,都知道的,看人家模板是怎么用的,原理去大佬掘金的文章上看:
首先写一个svg-icon
组件:
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
// isExternal 是一个正则检验 return /^(https?:|mailto:|tel:)/.test(path)
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
然后在阿里巴巴iconfont下载你需要的icon格式为svg,存在一个文件夹下,然后写一个js文件注册这个组件:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/) // 这里./svg是存放你的svg格式的icon的文件夹
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
然后使用:
// 这个icon-class="man",man就是你要用的svg的名字
<svg-icon icon-class="man" style="width:40px;height:40px"></svg-icon>
还没有评论,来说两句吧...