October 30, 2024
Vue js da Icon lar bilan ishlash uchun eng samarali yo'l
Albatta har bir project da icon bilan ishlashda muammo lar bo'lishi mumkun yoki siz tanlagan yo'lingizni kerakli darajada samarali emas deb o'ylasangiz xozir taklif qiladigan yo'lim juda foydali bo'ladi.
BaseIcon (Vue best practise dan kelib chiqilganda component nomi VIcon ham bo'lishi mumkun) - bu shunday component ki unga props orqali icon nomi berilganda o'zi kerakli icon ni async import qilib oladi.
shared/UI/base-icon/BaseIcon.vue
<script setup> import useBaseIcon from "./useBaseIcon"; // project TypeScript da bo'lsa yana ham yaxshi // props larni default qilib bersa bo'ladi const props = defineProps(["icon", "size", "color"]); // Icon - icon ning nomi // Size - icon size yani props dan kerakli size ni bersangiz bo'ladi // Color - icon ni rangi, bu uchun svg file da currentColor bo'lishi kerak const { SVGComponent, isSlot } = useBaseIcon(props); </script>
<template> <i class="base-icon" :style="{ color: props.color, fontSize: size ?? '24px' }" > <template v-if="isSlot"> <slot /> </template> <SVGComponent v-else /> </i> </template>
<style lang="scss" scoped> .base-icon { svg { font-size: inherit; width: 100%; // width va height bu icon ga tepadan size berilganda - height: 100%; // icon to'liq chiqishi uchun } } </style>
shared/UI/base-icon/useBaseIcon.js
import { computed, defineAsyncComponent } from "vue"; export default function useBaseIcon(props) { // Bu yerda slot orqali BaseIcon ni image xolatda render qilsa ham bo'ladi const isSlot = computed(() => typeof props.icon !== "string"); // Bu yerda svg file async xolatda import bo'ladi, props.icon ga qarab const SVGComponent = computed(() => props.icon && defineAsyncComponent( () => import(`@/assets/icons/${props.icon}.svg`))); // @/assets/icons ni o'rniga icon lar turgan folder ni berasiz return { SVGComponent, isSlot, } }
Eslatma! Bu yo'nalish Vue 3 chi versiya uchun ishlidi, Vue 2 da, Vue 2.7 gacha project ni ko'tarib vue-composition-api plugin ni o'rganib shu bilan ham qilsa bo'ladi, va Albatta test yozishni unutmang va @vite-svg-loader plugin esdan chiqmasin
Yo'nalish yoqqan bo'lsa qo'llab quvvatlash uchun - https://tirikchilik.uz/@sheyxuz