首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

vue3 封装element图标组件

Sonder
2023-03-29
2120字
5分钟
浏览 (1.2k)

封装组件 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',
 }"
/>

效果

image.png
image.png
下一篇 / 使用better-scroll完成自动滚动

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)