如何通过laravel livewire和分页来解决奇怪的行为? app / Http / livewire / posts / Posts.php中的组件代码视图1:resources / views / livewire / posts / posts.blade.php中的主页 2-在资源/视图/livewire/posts/create.blade.php中创建包含更新包含

如何解决如何通过laravel livewire和分页来解决奇怪的行为? app / Http / livewire / posts / Posts.php中的组件代码视图1:resources / views / livewire / posts / posts.blade.php中的主页 2-在资源/视图/livewire/posts/create.blade.php中创建包含更新包含

几天前,我开始使用Laravel 8和livewire。我还有很多发现,但我正在路上。

最后,我遇到了无法理解的行为。

我的目标

我想创建一个包含CRUD帖子的页面。我想要的是在页面底部显示分页显示的帖子列表,创建新帖子的按钮以及单击每个帖子行上的按钮以编辑帖子的可能性。 我还希望隐藏列表的同时在页面顶部显示帖子的编辑器(但这并不是绝对必要的)。

只要帖子列表没有分页但没有分页,我就可以设法使它工作。

为此,我使用一个liveewire组件,其代码如下:

app / Http / livewire / posts / Posts.php中的组件代码

<?php
namespace App\Http\Livewire\Posts;
use App\Models\Post;
use Livewire\Component;
class Posts extends Component
{
    public $posts;
    public $links;
    public $post_id,$title,$abstract,$body,$category,$diaporama_dir,$beg_date,$end_date,$close_date,$receive_registration,$sticky,$user_id,$inscription_directive;   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public  function render()
    {   
        $this->mode='list';
        $this->posts=Post::select('id','title')->orderBy('created_at','DESC')->paginate(15)->toArray();
        $this->links=$this->posts['links'];
        //dd($this->links);
        $this->user_id=auth()->user()->id;
        return view('livewire.posts.posts');
    }
    public function donothing(){

    }
    /*
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function resetInputFields(){
        $this->title = '';
        $this->body = '';
        $this->title='';
        $this->abstract='';
        $this->body='';
        $this->category='';
        $this->diaporama_dir='';  
        $this->beg_date='';
        $this->end_date='';
        $this->close_date='';
        $this->receive_registration='';
        $this->sticky='';
        
        $this->inscription_directive='';
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        
        $validatedData = $this->validate([
            'title' => 'required','body' => 'required','abstract'=>'required','category'=>'','diaporama_dir'=>'','beg_date'=>'sometimes','end_date'=>'sometimes','close_date'=>'sometimes','receive_registration'=>'','sticky'=>'','user_id'=>'required','inscription_directive'=>''
        ]);
        Post::create($validatedData);
        session()->flash('message','Bravo ! Votre article a été enregistré.');
       // $this->resetInputFields(); //user may want to keep the input stable
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $post = Post::findOrFail($id);
        $this->post_id = $id;
        $this->title = $post->title;
        $this->abstract=$post->abstract;
        $this->body=$post->body;
        $this->category=$post->category;
        $this->diaporama_dir=$post->diaporama_dir;  
        $this->beg_date=$post->beg_date;
        $this->end_date=$post->end_date;
        $this->close_date=$post->close_date;
        $this->receive_registration=$post->receive_registration;
        $this->sticky=$post->sticky;
        $this->inscription_directive=$post->inscription_directive;

        $this->dispatchBrowserEvent('notify','je passe en mode edit');//to switch browser page to edit mode
    }


        /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function update()
    {
        $validatedData = $this->validate([
            'title' => 'required','inscription_directive'=>''
        ]);

        $post = Post::find($this->post_id);
        $post->update([
            'title' => $this->title,'body'=> $this->body,'abstract'=> $this->abstract,'category'=> $this->category,'diaporama_dir'=>$this->diaporama_dir,'beg_date'=>$this->beg_date,'end_date'=>$this->end_date,'close_date'=>$this->close_date,'receive_registration'=>$this->receive_registration,'sticky'=>$this->sticky,'user_id'=>$this->user_id,'inscription_directive'=>$this->inscription_directive
        ]);
      
        session()->flash('message',"Bravo ! L'article a été mis à jour.");

       // $this->resetInputFields();//user may like to keep the input fields stable

    }
}

视图如下:

视图1:resources / views / livewire / posts / posts.blade.php中的主页

<div class="container m-auto  w-10/12">
<div x-data="{ mode: 'list' }">
    @if (session()->has('message'))
        <div class="bg-green-200 p-4 w-full my-8 text-xl text-orange-500">
            {{ session('message') }}
        </div>
    @endif
    <div x-on:notify.window="mode = 'update'">
        <div x-show="mode==='update'">
            @include('livewire.posts.update')
        </div>

        <div x-show="mode === 'edit'">
            @include('livewire.posts.create')
        </div>
    </div>

   {{-- <div x-show="mode === 'list'" class="">--}} 
       <div>
        <div>
            <button x-on:click="mode = 'edit'" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Nouvel
                article</button>

        </div>
        <table class=" bg-green-400 w-full table table-bordered mt-5 ">
            <thead>
                <tr class="bg-red-50 mb-2">
                    <th>Id.</th>
                    <th>Titre</th>
                    <th width="150px">Action</th>
                </tr>
            </thead>
            <tbody>

                @for ($i = 0; $i < $posts['per_page']; $i++)
                    <tr class="bg-red-400 mb-2 p-2 space-y-2 border-8 border-red-50 ">
                        <td>{{ $posts['data'][$i]['id'] }}</td>
                        <td>{{ $posts['data'][$i]['title'] }}</td>
                        <td>{{--les actions--}}
                            <button wire:click="edit({{ $posts['data'][$i]['id'] }})"
                                class="btn btn-primary btn-sm">Edit</button>
                            {{-- <button wire:click="delete({{ $post->id }})"
                                class="btn btn-danger btn-sm">Delete</button>--}}
                        </td>
                    </tr>
                @endfor
            </tbody>
        </table>
        <div class="flex flex-row mt-2">
            @for ($i = 0; $i < count($links); $i++)
                <div class="flex p-2 mr-2 border w-max-content">
                     <a href="{{$links[$i]['url'] }}">{{$links[$i]['label']}}</a>

                </div>
            @endfor
        </div>
    </div>
</div>

2-在资源/视图/livewire/posts/create.blade.php中创建包含

<div class="container bg-green-500 p-4">
    <form>
        This is the create form
        <input type="hidden" name="user_id" wire:model="user_id" >
        <div class="flex flex-col md:flex-row" >
        <div class=" mt-2 flex flex-col w-max-content">
            <label for="category">Catégorie:</label>
            <select class="" name="category" id="category" wire:model="category">
                <option value="Sans">Sans</option>
                <option value="Annoncement">Annonce d'un événement</option>
            </select>
            @error('category') <span class="text-danger">{{ $message }}</span>@enderror
        </div>
        <div class=" mt-2 flex flex-col flex-auto ml-4">
            <label for="title">Title:</label>
            <input type="text" class="form-control" name="title" id="title" placeholder="Saisissez un titre"
                wire:model="title" value="">
            @error('title') <span class="text-danger">{{ $message }}</span>@enderror
        </div>

    </div>
    <div class="flex flex-col md:flex-row" >
        <div class=" mt-2 flex flex-col w-max-cbeg_date ">
            <label for="beg_date">Date de début</label>
            <input type="text" class="" name="beg_date" id="beg_date" wire:model="beg_date">          
            @error('beg_date') <span class="text-danger">{{ $message }}</span>@enderror
        </div>
        <div class=" mt-2 flex flex-col w-max-cbeg_date ml-4">
            <label for="end_date">Datend_date</label>
            <input type="text" class="" name="end_date" id="end_date" wire:model="end_date">
            @error('end_date') <span class="text-danger">{{ $message }}</span>@enderror
        </div>
        <div class=" mt-2 flex flex-col w-max-cbeg_date ml-4">
            <label for="close_dclose">Date limite</label>
            <input type="text" class="" name="close_date" id="close_date" wire:model="close_date">
            @error('close_date') <span class="text-danger">{{ $message }}</span>@enderror
        </div> 
        <div class=" mt-2 flex flex-col w-max-content ml-4">
            <label for="receive_registration">Accepte les inscriptions:</label>
            <select class="" name="receive_registration" id="receive_registration" wire:model="receive_registration">
                <option value="no">Non</option>
                <option value="yes">Oui</option>
            </select>
            @error('receive_registration') <span class="text-danger">{{ $message }}</span>@enderror
        </div>
        <div class=" mt-2 flex flex-col flex-auto ml-4">
            <label for="title">Dossier du diaporama</label>
            <input type="text" class="form-control" name="diaporama_dir" id="diaporama_dir" placeholder="ex: admin/1"
                wire:model="diaporama_dir">
            @error('diaporama_dir') <span class="text-danger">{{ $message }}</span>@enderror
        </div>
    </div>
    <div class="mt-2 flex flex-col">
        <label for="abstract">Résumé</label>
        <textarea  class="form-control" name="abstract" id="abstract" wire:model="abstract"
            placeholder="Saisissez votre article"></textarea>
        @error('abstract') <span class="text-danger">{{ $message }}</span>@enderror
    </div>

    <div class="mt-2 flex flex-col">
        <label for="body">Corps de l'article</label>
        <textarea  class="form-control" name="body" id="body" wire:model="body" rows=30
            placeholder="Saisissez votre article"></textarea>
        @error('body') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <button wire:click.prevent="store()" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Enregistrer</button>
    <button wire:click.prevent="resetInputFields()" class="bg-red-400 px-2 py-1 border rounded-lg mt-2">Effacer tout</button>
    <button @click.prevent="mode = 'list'" class="bg-red-400 px-2 py-1 border rounded-lg mt-2 ml-16">Retour à la liste</button>
</form>

更新包含

更新包含与创建包含完全相同,除了帖子ID的其他隐藏字段。

发生了什么事?

在启动时,我的意思是当我访问 localhost:8000 / posts 页面时,页面1正确显示,并且页面底部的链接类似于 localhost:8000 / posts?page = 3 可能是页面的多少。

通常,我可以从此页面使用底部链接转到另一页,多次。

单击链接编辑帖子时出现问题。服务器已正确发送了该帖子,但是我们立即切换到了分页帖子的第1 页,并且底部链接采用一种奇怪的形式,例如 > localhost:8000 / livewire / message / posts.posts?page = 3

在显示创建表单后,在字段中键入第一个字符时,也会出现问题。实际上,似乎每次需要同步时都会出现。

我该如何解决?

解决方法

替换

<div class="flex flex-row mt-2">
    @for ($i = 0; $i < count($links); $i++)
        <div class="flex p-2 mr-2 border w-max-content">
             <a href="{{$links[$i]['url'] }}">{{$links[$i]['label']}}</a>

        </div>
    @endfor
</div>

使用

<div class="flex flex-row mt-2">
    {{ $posts->links() }}
</div>

和组件

use WithPagination;

参考链接https://laravel-livewire.com/docs/2.x/pagination

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-