Element Plus中SvgIcon引入和使用(Vue项目)
1、在项目src/components/SvgIcon中添加index.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" :fill="color"/>
</svg>
</template>
<script>
export default defineComponent({
props:{
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
color: {
type: String,
default: ''
}
},
setup(props) {
return {
iconName: computed(()=> `#icon-${props.iconClass}`),
svgClass: computed(()=> {
if(props.className){
return `svg-icon ${props.className}`
}
return 'svg-icon'
})
}
}
})
</script>
<style scope lang="scss">
.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>
2、在项目src/components/SvgIcon中添加svgicon.js
import * as components from '@element-plus/icons-vue'
export default {
install: (app) => {
for (const key in components) {
const componentConfig = components[key];
app.component(componentConfig.name, componentConfig);
}
},
};
3、在main.js文件中注册
import { createApp } from 'vue'
import App from './App'
import directive from './directive'
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon'
import elementIcons from '@/components/SvgIcon/svgicon'
const app = createApp(App)
app.use(elementIcons)
app.component('svg-icon', SvgIcon)
directive(app)
app.mount('#app')
4、使用
<template>
<el-button link type="primary" icon="View" ></el-button>
</template>
<script>
</script>
<style scoped>
</style>