【问题标题】:Livewire: pass a dom elements value to a livewire actions handler as a parameter?Livewire:将 dom 元素值作为参数传递给 livewire 操作处理程序?
【发布时间】:2021-03-06 11:36:26
【问题描述】:

刚刚试用 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
        ]);
    }
}

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案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
        }
    

    Bing body 到 textarea 并删除参数。

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

    【讨论】:

      猜你喜欢
      • 2015-06-11
      • 2021-09-02
      • 2013-11-15
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2023-01-27
      • 1970-01-01
      相关资源
      最近更新 更多