多字变量可以传递给刀片组件吗?

问题描述 投票:0回答:2

我使用

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 Test extends Component
{
    public $test_id;

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

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

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

php laravel laravel-blade
2个回答
1
投票

Livewire 组件不支持经典的

__construct
构造函数。相反,你最好使用
mount()
方法

此外,您应该使用这样的公共财产

public $test_id;

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

并在您的视图中使用引用(请参阅数据绑定

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

我通常会选择

camelCase
命名,f。前任。
testId
。 Livewire 绝对支持这一点(请参阅docs)。

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

您用一个单词多单词描述的变量被命名为

更新评论组件

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
方法中。只需使用公共财产即可。


1
投票

我也面临同样的问题。我无法将

:dd_array="$dd_color"
传递给匿名刀片组件,但像
:ddArray="$dd_color"
那样传递它效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.