laravel 是否可以将多字变量传递给刀片组件?

pcww981p  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(121)

我使用php artisan make:component Test创建了一个新组件。现在,在创建该组件时,如果我尝试传递一个单词变量,一切都正常(<x-test :testID="'test'")。但是当我尝试将它作为多个单词传递时,使用下划线(<x-test :test_id="'test'")分隔单词,我面临下一个错误:

  1. Unresolvable dependency resolving [Parameter #0 [ <required> $test_id ]] in class App\View\Components\Test

这个类看起来像这样:

  1. class Test extends Component
  2. {
  3. public $test_id;
  4. public function __construct($test_id)
  5. {
  6. $this->test_id = $test_id;
  7. }
  8. public function render()
  9. {
  10. return view('components.test');
  11. }
  12. }

这是正常的行为吗?在组件内部创建变量时,是否允许使用下划线?

zxlwwiss

zxlwwiss1#

Livewire组件不支持经典的__construct构造函数。最好使用mount()方法。
此外,您应该像这样处理公共属性

  1. public $test_id;
  2. public function mount()
  3. {
  4. // properly initialize the var
  5. $this->test_id = 0;
  6. }

并在视图中引用(参见数据绑定)它,

  1. <x-test wire.model="test_id"/>

我通常会选择camelCase命名,f。例如testId。这在Livewire中是完全支持的(参见docs)。

一些关于变量命名的一般提示

你用 * 一个词 * 和 * 多个词 * 变量描述的东西被命名为

  • 卡梅尔凯斯湾例如myVariableNameWikipedia
  • 斯内克凯斯湾例如my_variable_nameWikipedia

更新注解组件

  1. class Comments extends Component
  2. {
  3. public int $postId;
  4. public function mount()
  5. {
  6. $this->postId = 0;
  7. }
  8. public function render()
  9. {
  10. $comments = Comments::where('post_id', $this->postId)->get();
  11. return view('post.list', [
  12. 'comments' => $comments,
  13. ]);
  14. }
  15. }

在你看来,你可以使用这样的东西。

  1. <x-comments :postId="$post->id"/>

你不需要将它注入到mount方法中。只是使用公共财产。

展开查看全部
bejyjqdl

bejyjqdl2#

我也面临同样的问题。我不能将:dd_array="$dd_color"传递给匿名刀片组件,但像:ddArray="$dd_color"一样传递它可以正常工作。

相关问题