Провод laravel Livewire: щелкните, чтобы не запускать функцию

Я хочу сделать SPA с laravel livewire, я хочу использовать провод: щелкните, чтобы запустить функцию в компоненте, но он не работает, извините, если код испортил мою первую публикацию здесь, и я не уверен, что опубликовать вот мой код, чтобы решить эту проблему, спасибо

main.blade.php

@section('content')
<div>
    <div class="row justify-content-center">
        <div class="col-12">
            <div class="card my-3">

                        <!-- header -->
                <div class="card-header d-inline-flex">
                    <h3 class='mr-2'>Categories</h3>
                    <div>
                        <a href="javascript:void(0);" wire:click='createCategory' class="btn btn-success ">Add NewCategory</a>
                    </div>
                </div><!-- header -->
                <div class="card-body">

                    <!-- alerts -->
                    @include('admin.includes.alerts.errors')
                    @include('admin.includes.alerts.success')
                    <!-- alerts -->


                    <!-- if True , create form will show , if not will stay disabled -->
                    @if ($showCreateForm)
                    @livewire('admin.category.create' )
                    @endif
                    <!-- if True , create form will show , if not will stay disabled -->

                    <!-- Table -->
                    <div class="table-responsive">
                        <table id="example2" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Image</th>
                                    <th>Name</th>
                                    <th>Slug</th>
                                    <th>Status</th>
                                    <th>Parent</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($categories as $category)
                                <tr>
                                    <td>{{$category->id}}</td>
                                    {{-- <td>{{storage_path(app\livewire-tmp\$category->image)}}" /></td> --}}
                                    <td>{{$category->name}}</td>
                                    <td>{{$category->slug}}</td>
                                    <td class=" {{$category->isActive()==='Active'? 'text-success':'text-danger'}}">
                                        {{$category->isActive()}}</td>
                                    <td>{{ !empty($category->parent) ? $category->parent->name:'' }}</td>
                                    <td>
                                        <a href="" class="btn btn-warning">Edit</a>
                                        <a href="" class="btn btn-danger">Delete</a>
                                    </td>
                                </tr>
                                @endforeach

                            </tbody>
                            <tfoot>
                                <tr>
                                    <th>ID</th>
                                    <th>Image</th>
                                    <th>Name</th>
                                    <th>Slug</th>
                                    <th>Status</th>
                                    <th>Parent</th>
                                    <th>Action</th>
                                </tr>
                            </tfoot>
                        </table>
                        <div>
                            {!!$categories->links()!!}
                        </div>
                    </div>
                    <!-- Table -->

                </div><!-- body -->
            </div>
        </div>
    </div>
</div>
@endsection

и компонент Main.php,

<?php

namespace App\Http\Livewire\Admin\Category;

use App\Models\Admin\Category;
use Livewire\Component;
use Livewire\WithPagination;

class Main extends Component
{
    use WithPagination;

    protected $categories;
    public $showCreateForm = false;
    public $showEditForm = false;
    public function render()
    {
        $categories = Category::orderBy('id','desc')->paginate(12);
        return view('livewire.admin.category.main',[
            'categories' => $categories,
        ]) ->layout('layouts.admin');
    }

    public function createCategory()
    {
         $this->showCreateForm = !$this->showCreateForm;
    }
    public function update_Category($id)
    {


         $categories = Category::whereId($id);
         if ($categories) {
            $this->emit('getCategoryid' , $categories);
            $this->showEditForm = !$this->showEditForm;
            $this->showCreateForm = false;
         }
    }
    public function delete_Category($id)
    {
         $this->showCreateForm = !$this->showCreateForm;
    }
}
  • //// Обновление ////

Я попробовал iRestWeb Answer, я думаю, что это правильный ответ, но я даже не понимаю, что происходит с его 100% -ным javascript, и это не моя область знаний, поэтому вот мой полный код, я надеюсь, что кто-то поймет, и снова извините, если мой код беспорядочный и доставляю вам неприятности, спасибо.

create.blade.php

<div>
  <form role="form" wire:submit.prevent="create" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="card-body">
      <div class="row">
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputEmail1">Parent</label>
            <select type="select" class="form-control" id="exampleInputEmail1" wire:model="parent_id" name="parent_id">
              <option selected value> -- select an option -- </option>
              {{-- @if (is_array($categories) || is_object($categories) || !empty($categories)) --}} @foreach ($categories as $category)
              <option value="{{$category->id}}">{{$category->name}}</option>
              @endforeach {{-- @endif --}}
            </select>
          </div>
        </div>
        <!-- 1 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputPassword1">Category Name</label>
            <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="name" name="name"> @error('name') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <!-- 2 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputPassword1">Slug Name</label>
            <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="slug" name="slug"> @error('slug') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <!-- 3 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleFormControlFile1">Image</label>
            <input type="file" wire:model="image" class="form-control-file" id="exampleFormControlFile1" name="image"> @error('image') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>

        </div>
        <!-- 4 -->
      </div>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" id="exampleCheck1" wire:model="is_active" name="is_active">
        <label class="form-check-label" for="exampleCheck1">is Active</label> @error('is_active') <span class="error text-danger">{{ $message }}</span> @enderror
      </div>
    </div>
    <!-- /.card-body -->
    <div class="card-footer">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </form>
</div>

Create.php

<?php

namespace App\Http\Livewire\Admin\Category;

use Livewire\Component;
use App\Models\Admin\Category;
use Livewire\WithFileUploads;
use Illuminate\Support\Str;
use Livewire\WithPagination;
use Intervention\Image\Facades\Image;



class Create extends Component
{


use WithFileUploads;
    use WithPagination;

    public $slug , $name , $image , $parent_id , $is_active;

    protected $rules = [
        'slug' => 'required|unique:categories,slug',
        'name' => 'required',
        'image'=> 'nullable|image|max:1024'
    ];

    protected $categories;
    public function render()
    {
        $categories = Category::orderBy('id','desc')->paginate(12);
        return view('livewire.admin.category.create' , [
            'categories' => $categories,
        ]);
    }
    public function create()
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'slug' => $this->slug,
            'is_active'=> $this->is_active,
            'image'=> $this->image,
            'parent_id'=> $this->parent_id,
        ];
        //image upload
            try {
                if ($image = $this->image) {
                    $filename = Str::slug($this->name).'.'.$image->getClientOriginalExtension();
                    $path = public_path('assets/image/'.$filename);
                    Image::make($image->getRealPath())->save($path,100);
                }
                Category::create($data);
                $this->reset();
                return $this->addError('success' , 'Created Successfuly');
            } catch (\Throwable $th) {
                return $this->addError('error', 'Something Wrong Happens');
            }

    }

}

edit.blade.php

<div>
  <form role="form" method="POST" enctype="multipart/form-data" wire:submit.prevent="update">
    @csrf
    <div class="card-body">
      <div class="row">
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputEmail1">Parent</label>
            <select type="select" class="form-control" id="exampleInputEmail1" wire:model="parent_id" name="parent_id">
              <option></option>
              {{-- @if (is_array($categories) || is_object($categories) || !empty($categories)) --}} @foreach ($categories as $category)
              <option value="{{$category->id}}">{{$category->name}}</option>
              @endforeach {{-- @endif --}}
            </select>
          </div>
        </div>
        <!-- 1 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputPassword1">Category Name</label>
            <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="name" value='{{$category->name}}' name="name"> @error('name') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <!-- 2 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleInputPassword1">Slug Name</label>
            <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Name" wire:model="slug" name="slug" value='{{$category->slug}}'> @error('slug') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <!-- 3 -->
        <div class="col-6">
          <div class="form-group">
            <label for="exampleFormControlFile1">Image</label>
            <input type="file" class="form-control-file" id="exampleFormControlFile1" name="image">
            <img value='{{$category->image}}' alt="" srcset=""> @error('image') <span class="error text-danger">{{ $message }}</span> @enderror
          </div>

        </div>
        <!-- 4 -->
      </div>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" id="exampleCheck1" wire:model="is_active" name="is_active">
        <label class="form-check-label" for="exampleCheck1">is Active</label> @error('is_active') <span class="error text-danger">{{ $message }}</span> @enderror
      </div>
    </div>
    <!-- /.card-body -->
    <div class="card-footer">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </form>
</div>

Edit.php (незавершенная задача)

<?php

namespace App\Http\Livewire\Admin\Category;

use Livewire\Component;
use App\Models\Admin\Category;

class Edit extends Component
{
    protected $categories , $cat_id;
    public $slug , $name , $image , $old_image , $parent_id , $is_active;

    protected $listeners = ['getCategoryid'=>'getID'];


    public function mount()
    {
       $this->categories = Category::whereId($this->cat_id)->first();
    }//mout


    public function render()
    {
        $categories = Category::all();
        return view('livewire.admin.category.edit' , [
            'categories' => $categories,
        ]);
    }//render

    public function update($id)
    {

    }//update

    public function getID($categories)
    {
        $this->categories = $categories;

        // Data
        $this->slug = $this->$categories['slug'];
        $this->name = $this->$categories['name'];
        $this->image = $this->$categories['image'];
        $this->old_image = $this->$categories['old_image'];
        $this->parent_id = $this->$categories['parent_id'];
        $this->is_active = $this->$categories['is_active'];

    }//getID
}


person Mustafa Khaled    schedule 27.09.2020    source источник
comment
добро пожаловать, что вы имеете в виду, говоря, что не работает, расскажите больше об ошибке, которая показывает   -  person bhucho    schedule 27.09.2020
comment
ссылка в заголовке карты должна перейти и запустить функцию в компоненте Main.php, поэтому, когда я нажимаю на нее, она ничего не делает   -  person Mustafa Khaled    schedule 27.09.2020
comment
В вашей консоли есть ошибки?   -  person Qirel    schedule 27.09.2020
comment
В сети ничего не происходит, в консоли нет ошибок   -  person Mustafa Khaled    schedule 27.09.2020
comment
проверьте вкладку сети, он отправляет что-нибудь?   -  person RayanFar    schedule 29.01.2021


Ответы (4)


Весь HTML-код должен быть покрыт одним <div>. Тогда все заработает.

person selvan    schedule 18.02.2021
comment
это сработало для меня, спасибо - person paqstd; 24.03.2021
comment
Вы сделали мой день! Спасибо - person eleftrik; 15.06.2021

добавьте liveWire css и js в файл base.blade.php, и он заработает:

<head>
...
    @livewireStyles
</head>
<body>
    ...

    @livewireScripts
</body>
</html>
person RayanFar    schedule 29.01.2021

Для этого вам не нужно событие :click, вы можете просто использовать:

wire:$toggle('property')

И вам не нужно использовать тег a; вы можете просто использовать тег button. Итак, код вашей кнопки будет выглядеть так:

<button type="button" wire:$toggle='showCreateForm' class="btn btn-success">Add New Category</button>
person iRestWeb    schedule 27.09.2020
comment
спасибо за ответ, я попробую и подтвердю, работает он или нет - person Mustafa Khaled; 27.09.2020
comment
это не сработало, приятель, я думаю, что это javascript, потому что он вообще не отвечает, как отключенная ссылка, это странно, очень странно - person Mustafa Khaled; 28.09.2020
comment
Вы включили css и js livewire? укажите полный код страницы, включая макет страницы - person iRestWeb; 28.09.2020

Я думаю это поможет тебе

<a href="#" wire:click.prevent="$toggle('showCreateForm')" class="btn btn-success">Add New Category</a>
person Shekh Saifuddin    schedule 16.12.2020