blade组件可以传多字变量吗?

Can multi word variable be passed to blade component?

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

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

class 看起来像这样:

class Test extends Component
{
    public $test_id;

    public function __construct($test_id)
    {
        $this->test_id = $test_id;
    }

    public function render()
    {
        return view('components.test');
    }
}

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

Livewire 组件不支持经典的 __construct 构造函数。相反,你最好使用 mount() method.

此外,您应该像这样使用 public 属性

public $test_id;

public function mount()
{
    // properly initialize the var
    $this->test_id = 0;
}

并在您的视图中引用(参见 Data Binding

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

我通常会选择 camelCase 命名,f。前任。 testId。 Livewire 绝对完全支持这一点(请参阅 docs)。

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

你用单词多词变量描述的内容被命名为

  • 驼峰式,f。前任。 myVariableNameWikipedia
  • 蛇案,f。前任。 my_variable_nameWikipedia

更新评论组件

class Comments extends Component
{
    public int $postId;

    public function mount()
    {
        $this->postId = 0;
    }


    public function render()
    {
        $comments = Comments::where('post_id', $this->postId)->get();

        return view('post.list', [
          'comments' => $comments,
        ]);
    }
}

在您看来,您可以使用类似这样的东西。

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

您不需要将其注入到 mount 方法中。只需使用 public 属性.

我遇到了同样的问题。我无法将 :dd_array="$dd_color" 传递给匿名 blade 组件,但像 :ddArray="$dd_color" 一样传递它就可以了。