【问题标题】:Laravel replace/convert @foreach loop to vue v-for loop with database relationshipLaravel 将 @foreach 循环替换/转换为具有数据库关系的 vue v-for 循环
【发布时间】:2024-05-04 15:10:04
【问题描述】:

我正在制作一个 laravel SPA,我最近学习了如何使用 vue,并且我知道 v-for 如何使用我的组件在 vue 中工作。我只知道如何只在一个没有关系的表中循环,这就是为什么我很难改变它。我有两张表newscomments,这张表news 里面有很多comments

我现在的刀片文件。

@foreach($news->comments as $comment)
<div class="comment" style="background-color: #f6efef;" >
<div class="author-info">
  <img src={{"https://www.gravatar.com/avatar/" . md5(strtolower(trim($comment->email))) . "?s=50&d=retro" }} class="author-image" id="image">
  <div class="author-name">
       <h4>{{$comment->name}} </h4>
       <p class="author-time"> {{  date('jS F, Y - g:iA' ,strtotime($comment->created_at)) }}</p>
  </div>
</div>
<div class="comment-content">
        {{$comment->comment}}
</div>
</div>
@endforeach

【问题讨论】:

    标签: laravel vue.js vue-component vue-router


    【解决方案1】:
    your component goes like this in vue2.0
    
    **block.vue**
    
    <template>
     <div class="comment" style="background-color: #f6efef;" v-for="comment in 
       news.comments" >
       <div class="author-info">
          <img :src="comment.author_image" }} class="author-image" id="image">
          <div class="author-name">
           <h4>{{ comment.name }} </h4>
           <p class="author-time"> {{ comment.time }}</p>
          </div>
        </div>
       <div class="comment-content">
            {{ comment.comment }}
       </div>
     </div>
    </template>
    <script>
    export default {
       name: "block",
       props: [ "news" ], //or
       data() => ({ news: [] })
    }
    </script>
    

    【讨论】:

    • 所以我应该只调用news 表并将其放在我脚本中的data 对象中吗? cmets怎么样?不需要放入data 对象?我有点困惑。
    • 您可以使用关系从控制器获取消息以及 cmets。语法类似于News::with('comments') -&gt;toArray();