我无法访问子组件中的父数据字段,当我将其添加为子组件中的公共属性时,它会擦除表单输入中的值。当我在子组件中设置公共$ amount属性时,金额字段将返回空值。
父视图
<div>
@foreach ($products as $product)
@livewire('orders', ['product'=> $product], key($product->id))
@endforeach
</div>
子视图
<div class="mt-8">
<div class="max-w-sm rounded overflow-hidden shadow-lg bg-white">
<div class="px-6 py-4">
<div class="font-bold text-xl mb-2 ">{{$product->id}}</div>
<hr><br>
<p class="text-gray-700 text-base">
<div class="font-bold text-lg mb-2">
{{$product->amount}}
</div>
<div class="relative">
<select wire:model="period" name="period"
class="block appearance-none w-full bg-white border border-gray-400 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-400">
<option value="5">5 Days</option>
<option value="7">7 Days</option>
<option value="10">10 Days</option>
</select>
@error('period')
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
@enderror
</div>
<br>
<div class="relative">
<input wire:model="amount"
class="appearance-none block w-full bg-white text-gray-700 border border-gray-400 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-gray-400"
type="text" value="{{$product->amount}}">
@error('amount')
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
@enderror
</div>
</div>
<div class="px-6 py-4">
<button wire:click.prevent="save({{$product->id}})"
class="inline-block bg-purple-700 rounded-full px-3 py-1 text-sm font-semibold text-gray-200 mr-2 transform motion-reduce:transform-none hover:-translate-y-1 hover:scale-110 transition ease-in-out duration-300">
Bid
</button>
</div>
</div>
</div>
父组件
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Product;
use App\User;
class Products extends Component
{
public $products;
public function mount()
{
$this->products = Product::all();
}
public function render()
{
return view('livewire.products');
}
}
子组件
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Order;
use App\Product;
class Orders extends Component
{
public $product, $period = 5, $productId, $amount;
public function mount(Product $product)
{
$this->product = $product;
}
public function save($productId)
{
$product = Product::where('id', $productId)->first();
$product->createOrders([
'buyer_id' => auth()->user()->id,
'product_id' => $this->productId,
'period' => $this->period,
'order_amount' => $this->amount,
]);
}
public function render()
{
return view('livewire.orders');
}
}