【问题标题】:Dynamicaly add or remove elements with livewire使用 livewire 动态添加或删除元素
【发布时间】:2021-06-12 08:50:15
【问题描述】:

LiveWire 中,我尝试在现有数组中添加一些值,我将其定义为component 中的一个字段,但是当我想在其中添加值时,在执行此操作后我有新数据,换句话说清除和设置新值的原因,例如:

class Students extends Component
{
    public $inputs = [];
    public $i = 1;

    public function add($i)
    {
        $i = $i + 1;
        $this->i = $i;
        array_push($this->inputs ,$i);
    }
 
    public function remove($i)
    {
        unset($this->inputs[$i]);
    }
}
<p wire:click="add(1)" class="t-text-lg">
    ...
</p>

这里当我调用add 函数时,input 的值总是2,每次调用add 函数都应该递增。

输出:

array:1 [▼
  0 => 2
]

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    由于您的逻辑,$i 的值始终为2

    wire:click="add(1)"
    
    public function add($i)
    {
        $i = $i + 1;
        $this->i = $i;
        array_push($this->inputs ,$i);
    }
    

    每次单击p 元素时,都会将值1 发送到add 函数,然后该函数只需添加1 并将其保存为$this-&gt;i 的新值。如果您检查您的 $inputs 数组,您会看到它填充了所有具有值 2 的元素。

    array:2 [▼
      0 => 2
      1 => 2
    ]
    

    你更可能想要的是:

    public function add($i)
    {
        $this->i = $this->i + $i;
        array_push($this->inputs, $this->i);
    }
    

    导致:

    array:2 [▼
      0 => 1
      1 => 2
    ]
    

    【讨论】:

    • 这段代码怎么样?它无法正常工作$this-&gt;productSizes[] = $this-&gt;productSizes + [str::random(10) =&gt; str::random(10)]; 我想在以前的数组上添加另一个选定的值,我将其作为属性:public array $productSizes=[]; 或者此代码是另一种解决方案:array_push($this-&gt;productSizes, [str::random(10) =&gt; str::random(10)]);
    • 它不起作用怎么办?似乎工作正常here
    • 当我尝试在livewire 组件中使用它来添加一些点击数据时,例如div 就像我的帖子一样,数据无法附加到数组中,我总是有一个新数组
    • @DolDurma 一定有其他因素影响您的代码,因为我无法重现该问题。
    • https://stackoverflow.com/questions/68016216/keeping-array-reference-and-adding-something-into-that
    【解决方案2】:
    public function add($i)
    {
        $this->i = $this->i + $i;
        array_push($this->inputs ,$this->i);
    }
    

    【讨论】:

    • 没有任何变化
    • 否,因为您的代码正在更新参数变量$i。所以,如果你用1 调用add,$i 总是2。你把它发送到$this-&gt;i。所以,它总是2
    • 解决方法是增加$this-&gt;i。所以,$this-&gt;i = $this-&gt;i + $i; 它正在增加。
    • 你能帮我解决这个问题吗? https://stackoverflow.com/q/68016216/1830228
    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2019-12-29
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多