【问题标题】:Livewire data binding issuesLivewire 数据绑定问题
【发布时间】:2021-01-04 04:26:32
【问题描述】:

我正在努力学习使用 livewire。所以我从文档和截屏开始。我正在使用带有 Livewire 脚手架的 Jetstream 构建一个 Laravel 项目。 问题似乎是控制器没有将变量传递给刀片模板。

我之前做了一个测试项目,只使用了 Laravel 8,修改了 welcome.blade.php 模板并需要 Composer 的 Livewire。而且效果很好。

重现步骤:创建一个 Laravel 8.x jetstream 项目并使用我的代码

这是我的代码:

在:App\Http\Livewire\AddPost.php:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class AddPost extends Component
{
    public $title = "Blank";
    public $content = "Such empty here";
    public function render()
    {
        return view('livewire.add-post');
    }
}

在:resources/views/add-post.blade.php

<html>
    <head>
        @livewireStyles
    </head>

    <body>
        @livewire('add-post')

        @livewireScripts
    </body>
</html>

在:resources\views\livewire\add-post.blade.php

<div>
    Title: {{ $title }}
    <br>
    Content: {{ $content }}
</div>

GitHub repo

【问题讨论】:

  • 无法在完全相同的文件夹中使用完全相同的代码复制此内容。你一定在做一些你没有在这里展示的事情。要么你打的是与外部不同的路线/视图,要么是其他的 - 因为代码本身有效。
  • 什么意思?我将发布一个 git hub repo,以便您检查所有内容,可以吗?
  • 您的路线错误。 Route::get('add-post', App\Http\Livewire\AddPost::class)-&gt;name('add-post'); 直接渲染 Livewire 组件,或者你应该返回外部视图,Route::get('add-post/', function () { return view('add-post'); })-&gt;name('add-post');
  • 工作。谢谢。我想我必须更好地研究路由

标签: php laravel laravel-livewire


【解决方案1】:

试试这个

public function render()
{
    return view('livewire.add-post', [
        'title' => $this->title,
        'content' => $this->content
    });
}

@livewire('add-post', ['title' => 'lorem ipsum', '' => 'content'])

或者使用这个函数,它就像一个constructor()。

public function mount() {
    $this->title = 'lorem ipsum';
    $this->content = 'content';
}

【讨论】:

    【解决方案2】:

    在 app.blade.php 中试试这个:{{$slot}}

     <html>
         <head>
             @livewireStyles
         </head>
     
         <body>
             {{ $slot }}                   <<<<<<<--------------
     
             @livewireScripts
         </body>
     </html>
    

    【讨论】:

      【解决方案3】:

      你可以用这个

      public $title;
      public $content;
      
      public function mount(){
      $this->title= "Blank";
      $this->content= "Such empty here";
      }
      

      【讨论】:

        猜你喜欢
        • 2011-01-17
        • 2017-02-16
        • 2011-10-18
        • 2011-09-12
        • 2011-04-08
        • 2014-05-25
        相关资源
        最近更新 更多