vue3 封装element图标组件
Sonder
2023-03-29
2120字
5分钟
浏览 (1.4k)
封装组件 CustomIcon
<template>
<el-icon ref="iconItem" :size="getAttr('size') || 0" :color="getAttr('color')" :class="getAttr('class')" >
<component v-bind:is="components" ></component>
</el-icon>
</template>
<script>
import { defineAsyncComponent } from 'vue'
import { ElIcon } from 'element-plus'
export default {
name:"CustomIcon",
props:{
icon:String,
params:{
type:Object,
default:()=>{
return {}
}
},
},
components:{
ElIcon
},
computed:{
components(){
return defineAsyncComponent(async ()=>{
console.log(`@element-plus/icons/types/${this.icon}`)
let item = await import(`@element-plus/icons`)
return item[this.icon]
})
}
},
methods:{
getAttr(key){
return this.params[key] || ""
}
}
}
</script>
如果使用setup模式
<template>
<el-icon ref="iconItem" :size="getAttr('size') || 0" :color="getAttr('color')" :class="getAttr('class')">
<component :is="components"></component>
</el-icon>
</template>
<script setup>
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { computed } from 'vue'
const props = defineProps({
icon: String,
params: {
type: Object,
default: () => ({})
}
})
const components = computed(() => {
return ElementPlusIconsVue[props.icon]
})
const getAttr = (key) => {
return props.params[key] || ""
}
</script>
如果你是全局使用的话
<script setup>
import { computed } from 'vue'
const props = defineProps({
icon: String,
params: {
type: Object,
default: () => ({})
}
})
const components = computed(() => {
return props.icon
})
const getAttr = (key) => {
return props.params[key] || ""
}
</script>
使用
import CustomIcon from "@/components/unit/CustomIcon";
<CustomIcon
icon="StarFilled"
:params="{
size: 20,
color: '#a1d042',
}"
/>