【问题标题】:Can multi word variable be passed to blade component?可以将多字变量传递给刀片组件吗?
【发布时间】:2021-04-27 18:29:49
【问题描述】:

我使用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');
    }
}

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

【问题讨论】:

    标签: laravel laravel-blade laravel-8


    【解决方案1】:

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

    【讨论】:

    • 是的,它就是这样工作的。接受像骆驼壳这样的接缝,但不接受蛇壳
    【解决方案2】:

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

    此外,您应该使用这样的公共属性

    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。前任。 myVariableName, Wikipedia
    • 蛇形盒,f。前任。 my_variable_name, Wikipedia

    评论组件更新

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

    【讨论】:

    • 谢谢你,我的错。我真正想做的是下一步。我正在创建一个博客,现在我需要让它能够将 cmets 放在每个帖子上。我想将$post-&gt;id 传递给我创建的组件&lt;x-comment :post_id="$post-&gt;id" /&gt;(那是我在上面调用的x-test)。因此,根据您的回答,我的下一个问题是 - 我可以将参数传递给 mount() 函数,以便稍后初始化 var?
    猜你喜欢
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2022-01-01
    • 2022-01-24
    相关资源
    最近更新 更多