提问者:小点点

Livewire:将dom元素值作为参数传递给Livewire操作处理程序?


只是尝试一下Livewire,一路上我被卡住了。我到了需要传递dom元素值的阶段,但不确定这样做的最佳实践是什么,甚至不确定是否可以通过livewire?

视图:

<div>
    <textarea class="form-control mb-3" wire:keydown.enter="addComment('Guest', 'This textareas value here')"></textarea>
    <hr>
    @foreach ($comments as $comment)
        <div class="card mt-4" style="background-color: deeppink">

            <div class="card-body">
                <h5 class="card-title">{{ $comment['author'] }}</h5>
                <p class="card-text">{{ $comment['body'] }}</p>
            </div>
        </div>
    @endforeach
</div>

组成部分:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Comments extends Component
{
    public $comments = [
        [
            'author' => 'John Doe',
            'body' => 'I really like short walks through the park near my house.',
        ],
        [
            'author' => 'Samantha Hox',
            'body' => 'Did you know, that Lions are actually bigger than the size you imagined. They are beautiful creatures so they are.',
        ],
    ];

    public function render()
    {
        return view('livewire.comments');
    }

    public function addComment($author, $body) {
        array_unshift($this->comments, [
            'author' => $author,
            'body' => $body
        ]);
    }
}

共1个答案

匿名用户

您只需使用wire:model=“$param”

    public $author = '';
    public $body = '';
    public $comments = [
        [
            'author' => 'John Doe',
            'body' => 'I really like short walks through the park near my house.',
        ],
        [
            'author' => 'Samantha Hox',
            'body' => 'Did you know, that Lions are actually bigger than the size you imagined. They are beautiful creatures so they are.',
        ],
    ];

    public function mount()
    {
        $this->author = 'Guest'; // set default value to Guest
    }

    public function render()
    {
        return view('livewire.comments');
    }

    public function addComment() {
        array_unshift($this->comments, [
            'author' => $this->author,
            'body' => $this->body
        ]);

        $this->reset(['body']);  // reset back to default value i.e. empty
    }

必应body文本区域并删除参数。

<textarea class="form-control mb-3" wire:model='body' wire:keydown.enter="addComment()"></textarea>