如何在递归 Laravel 组件中实现循环索引?

问题描述 投票:0回答:1

我陷入了一个问题,尝试了很多方法,但都是徒劳。 实际上我想要的是在递归 Laravel 组件中实现增量索引。 例如我希望索引是 0, 1, 2, 3, 4, 5, 6, 7, 8 ......等等。

我的代码是,

@foreach($costs as $cost)
   <x-estimation-item :cost="$cost" />
@endforeach

我的组件是,

@props([
    'cost',
])

<div>
    @foreach($cost->children as $child)
        <x-estimation-item :cost="$child" />
    @endforeach
</div>

我正在使用 Laravel Adjacency List 包,我的级别最多为 9 级。 现在我只想在每次组件调用时增加值。 我将访问子级的 foreach 循环之上的增量值。 知道我如何才能实现这一目标吗?

如果可能的话,任何想法或代码!

laravel laravel-8 laravel-blade
1个回答
0
投票

让您的

EstimationItem
组件接受反支撑。

App\View\Components\EstimationItem

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class EstimationItem extends Component
{
    public $cost;
    public $counter;

    public function __construct($cost, $counter) {
        $this->cost = $cost;
        $this->counter = $counter;
        $counter->increment();
    }
}

resources/views/components/estimation-item.blade.php

@props([
    'cost',
    'counter'
])

<div>
    @foreach($cost->children as $child)
        {{ $counter->value() }}
        <x-estimation-item :cost="$child" :counter="$counter" />
    @endforeach
</div>

声明一个

Counter
类来容器索引并在每次渲染组件时递增它。

App\Pojos\Counter

namespace App\Pojos;

class Counter {
    public function __construct() {
        $this->index = 0;
    }

    public function increment() {
        $this->index++;
    }
    public function value() {
        return $this->index;
    }
}

初始化计数器并将其作为支柱传递给您的组件。

@php
$counter = new \App\Pojo\Counter();
@endphp

@foreach($costs as $cost)
   {{ $counter->value() }}
   <x-estimation-item :cost="$cost" :counter="$counter" />
@endforeach

您可以在此处的操作中看到这一点

© www.soinside.com 2019 - 2024. All rights reserved.