【发布时间】:2021-11-19 01:12:32
【问题描述】:
我目前正在使用 Livewire 和 AlpineJS 开发一个项目。
我必须使用 contenteditable 设置为“true”的 div 来访问和修改我的数据模型。
我想要什么
我想使用 @entangle 在 Livewire 和 Alpine 之间共享状态。
我的代码
我的代码分为两部分。 第一部分依赖于full-Page component,我只是在其中注册了一组$fruits。 第二个是一个包含“表单”的组件,允许我通过 @entangle 和一个将 contenteditable 设置为 true 的 div 访问和修改数据。
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ListFruit extends Component
{
protected $listeners = ['addFruit'];
public array $fruits = [];
public function mount()
{
$this->addFruit();
}
public function addFruit()
{
$this->fruits[] = $this->makeBlankFruit();
}
public function makeBlankFruit(): array
{
return [
'type' => '',
'color' => ''
];
}
public function render()
{
return view('livewire.list-fruit');
}
}
views/livewire/list-fruit.blade.php 文件
<div class="w-full container mx-auto">
<h3 class="text-2xl font-sembibold">
Fruits
</h3>
<div id="fruits">
@foreach($fruits as $fruitIndex=> $fruit)
<livewire:fruit :fruitIndex="$fruitIndex" :fruit="fruit" :wire:key="$fruitIndex" >
@endforeach
</div>
</div>
水果成分
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Fruit extends Component
{
public array $fruit = [];
public string $fruitIndex;
public function render()
{
return view('livewire.fruit');
}
}
views/livewire/fruit.blade.php 文件
<div x-data="{type: @entangle('fruit.type'), color: @entangle('fruit.color')}"
x-init="console.log(type)"
>
<div>
<div x-on:blur="type = $event.target.innerHTML" contenteditable="true">{{ $fruit['type'] }}</div>
<div x-on:blur="color = $event.target.innerHTML" contenteditable="true">{{ $fruit['color'] }}</div>
</div>
<div>
$type @ Livewire: {{ $fruit['type'] }}
$color @ Livewire: {{ $fruit['color'] }}
</div>
<div>
type @ AlpineJS: <span x-text="type"></span>
color @ AlpineJS: <span x-text="color"></span>
</div>
</div>
如果我的主要组件中只有一个具有某些属性的数组,假设:
public array $fruit = [
'type' => '',
'color' => '',
];
我可以使用我的fruit.blade.php 访问它们
我也尝试过这样做。
{type: @entangle('fruits.'. $fruitIndex.'.color'), color: @entangle('fruits.'. $fruitIndex.'.type')}
我得到了什么
在我的 AlpineJs 组件中,我读取了一个 [object Object] 代理,并且在修改我的 fruit.color 或 fruit.type 属性时,livewire 部分没有更新。
我不知道为什么。 在我的最后一次尝试中,我尝试将我的水果分成多个子组件,以便我在一个数组上工作。
我正在寻找死胡同,所以提前感谢您的帮助。 狸猫
【问题讨论】:
标签: laravel laravel-blade laravel-livewire alpine.js