【问题标题】:Laravel Livewire calculate values on bladeLaravel Livewire 计算刀片上的值
【发布时间】:2021-05-16 21:08:19
【问题描述】:

我有一个动态刀片,我将值放入三个文本字段并将该值存储在数组中。

我的刀是这样的

在我的 Laravel Livewire 控制器中,我有以下代码

public $veriProducts = [];

public function render()
    {
        $products = Product::where('user_id', auth()->user()->id)
            ->orderBy( $this->sortBy, $this->sortAsc ? 'ASC' : 'DESC');
 
        $products = $products->paginate($this->perPage);
        
        info($this->veriProducts);

        return view('livewire.products', [
            'items' => $products,
        ]);

    }

  public function addProduct()
    {
        $this->veriProducts[] = ['price' => '', 'quantity' => ''];
    }

    public function removeProduct($index)
    {
        unset($this->veriProducts[$index]);
        $this->veriProducts = array_values($this->veriProducts);
    }

这是我的刀

<tbody>
@foreach ($veriProducts as $index => $orderProduct)
<tr>
<td>
<input type="number" name="veriProducts[{{$index}}][price]" class="border border-gray-300 form-control my-0 p-1 ring-blue-200 rounded-md" wire:model="veriProducts.{{$index}}.price" />
</td>
<td>
<input type="number" name="veriProducts[{{$index}}][quantity]" class="border border-gray-300 form-control my-0 p-1 ring-blue-200 rounded-md" wire:model="veriProducts.{{$index}}.quantity" />
</td>

<input type="number" name="veriProducts[{{$index}}][total]" class="border border-gray-300 form-control my-0 p-1 ring-blue-200 rounded-md" wire:model="veriProducts.{{$index}}.total" />
</td>

<input type="number" name="veriProducts[{{$index}}][pl]" class="border border-gray-300 form-control my-0 p-1 ring-blue-200 rounded-md" wire:model="veriProducts.{{$index}}.pl" />
</td>

</tr>
@endforeach

它工作正常我可以添加行,并且数组 $veriProducts 也可以正常创建。 数量文本框松散焦点或其他内容后如何计算总和盈亏

Total will be
price*quanrity

PL will be
20% less then total

非常感谢

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    假设 PLTotal 不可编辑,我们可以使用更新的挂钩并相应地设置 totalpl 值,

    
        public function updatedVeriProducts()
        {
            $this->veriProducts = collect($this->veriProducts)
                   ->map(function ($product) {
                       if ($product['price'] != '' && $product['quantity'] != '') {
                           $total = $product['price'] * $product['quantity'];
                           $product['total'] = round($total, 2);
                           $product['pl'] = round($total * 0.8, 2);
                       }
                       return $product;
                   })->toArray();
        }
    
    

    我已经利用 laravel 的 collect 方法轻松处理数组。

    使用if 条件,我们仅在pricequantity 都有一些输入值时才启用totalpl 的计算。

    为了避免小数过长,我使用round 函数将其四舍五入到小数点后两位。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2023-04-11
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 2019-07-29
      • 2021-03-15
      相关资源
      最近更新 更多