fix(categories): fix nested lvl > 2 categories rendering

This commit is contained in:
2025-09-24 15:02:37 +03:00
parent 9f6416a1b7
commit 0f04cbf105

View File

@@ -2,7 +2,7 @@
<div class="mx-auto max-w-2xl px-4 py-4 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8 mb-5 safe-top">
<h2 class="text-3xl mb-5">Категории</h2>
<button v-if="parentId" class="py-2 px-4 flex items-center mb-3 cursor-pointer" @click="goBack">
<button v-if="parentId && parentCategory" class="py-2 px-4 flex items-center mb-3 cursor-pointer" @click="goBack">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6 min-w-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18" />
</svg>
@@ -39,32 +39,37 @@ import {useRoute} from "vue-router";
import CategoryItem from "@/components/CategoriesList/CategoryItem.vue";
const route = useRoute();
const parentId = computed(() => route.params.id ? Number(route.params.id) : null);
const parentCategory = computed(() => findCategoryById(parentId.value));
const categoriesStore = useCategoriesStore();
function findCategoryById(id) {
for (const category of categoriesStore.categories) {
if (category.id === id) {
return category;
const parentId = computed(() => route.params.id ? Number(route.params.id) : null);
// 🔧 Рекурсивный поиск по всему дереву
function findCategoryById(id, list = categoriesStore.categories) {
if (id == null) return null;
for (const cat of list) {
if (cat.id === id) return cat;
if (cat.children?.length) {
const found = findCategoryById(id, cat.children);
if (found) return found;
}
}
return []
return null;
}
const categories = computed(() => {
if (! parentId.value) {
return categoriesStore.categories;
}
const parentCategory = computed(() => findCategoryById(parentId.value));
return findCategoryById(parentId.value).children;
// Если мы в корне — показываем корневые категории,
// если внутри — показываем детей найденной категории (или пустой массив, если не нашли)
const categories = computed(() => {
if (!parentId.value) return categoriesStore.categories;
return parentCategory.value?.children ?? [];
});
function onSelect(category) {
if (category.children.length === 0) {
router.push({ name: "product.categories.show", params: { category_id: category.id } });
if (!category?.children?.length) {
router.push({name: "product.categories.show", params: {category_id: category.id}});
} else {
router.push({ name: "category.show", params: { id: category.id } });
router.push({name: "category.show", params: {id: category.id}});
}
}
@@ -73,10 +78,12 @@ function goBack() {
}
function showProductsInParentCategory() {
router.push({ name: "product.categories.show", params: { category_id: parentId.value } });
if (parentId.value != null) {
router.push({name: "product.categories.show", params: {category_id: parentId.value}});
}
}
onMounted(async () => {
categoriesStore.fetchCategories();
await categoriesStore.fetchCategories();
});
</script>