簡體   English   中英

如何使用 laravel-livewire 對 2 個輸入值求和

[英]How can i sum 2 input values using laravel-livewire

我想總結2個值。

我的 livewire 刀片代碼:

<label>Sayı 1:</label>
<input type="text" id="a" name="a" wire:model.lazy="a">
<br>

<label>Sayı 2:</label>
<input type="text" id="b" name="b" wire:model.lazy="b">
<br>
Sonuç : {{ $result}}

在 livewire 文件中

public $result;
public $a;
public $b;

public function render()
{   
   $this->result=$this->a+$this->b;
    return view('livewire.try1');
}

我在我的頁面上看不到結果。

我改變$this->result=$this->a+$this->b; 行到$this->result=a+b; 它顯示了undefined variable $a

我打開了調試欄 a 和 b 為空。

所以我無法讓它工作。

首先,你的 Livewire 視圖應該總是包裹在一個 div 中,有點像這樣,

<div>
    <label>Sayı 1:</label>
    <input type="text" id="a" name="a" wire:model.lazy="a">

    <br>
    <label>Sayı 2:</label>
    <input type="text" id="b" name="b" wire:model.lazy="b">
    
    <br>
    Sonuç : {{ $result }}
</div>

然后我建議您使用生命周期掛鈎進行更新以維護結果,

public $result;
public $a;
public $b;

public function updated()
{
    $this->result = ($this->a ?? 0) + ($this->b ?? 0);
}

public function render()
{
    return view('livewire.try1');
}

此外,由於您的綁定上有lazy修飾符,請注意它不會更新,直到您點擊離開輸入,請參閱https://laravel-livewire.com/docs/2.x/properties#lazy-updating

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM