首页 > 解决方案 > Laravel 和 vue 无限加载器和分页问题

问题描述

我的项目:
我有很多帖子,索引方法返回分页帖子,每页3个。
但是,在我的 Vuejs 中,我不想显示页面,并且每次用户滚动到页面底部时,我都会使用无限滚动来显示接下来的 3 个帖子。
每次我删除帖子时,我都会使用 vue 实时删除它。页面不会刷新,帖子会被实时删除。

问题:
当我在前端加载帖子时,我加载了 3 个帖子,然后我删除了一个帖子,例如帖子 #1。

正如我们所知,laravel 中的第二页意味着转义前 3 个帖子并获得第二组 3 个帖子。

现在从数据库中删除了第一个帖子,当我转到页面底部时,我希望得到帖子 #4 #5 #6,但我会得到 #5 #6 #7。

原因:
因为一个帖子在数据库中消失了,而下一组 3 个帖子现在不同了。

但是如何解决这个问题? 这个问题有解决方案吗

标签: laravelapivue.jspaginationinfinite-scroll

解决方案


好吧,我认为最好的解决方案是在每次删除请求后更新 Posts 数组。只需在删除操作后立即使用当前页面发出 GET 请求并更新数组并将新值添加到现有数组(如果有)。现在我已经为它编写了一个示例代码,希望它会有所帮助。由于您没有共享代码,因此可能为您的组件编写代码

<template>
   <div>
      <div v-for="post in posts" :key="post._id">
          <div>{{post.name}}</div>
          <div>
             <button @click="deletePost(post)">Delete</button>
          </div>
      </div>
   </div>
</template>

<script>

import axios from "axios";

export default() {
   data() {
       current_page: 1,
       posts: []
   },

   created() {
        this.updatePosts();
   },

   methods: {
        updatePosts() {
            axios.get("http://www.example.com/posts"{
                params: {page: this.current_page}
            }).then(res => {
                if(res.status == '200') {
                    res.data.posts.forEach(post => {
                        if(!this.posts.includes(post)) this.posts.push(post);
                    });
                }
            }).catch(err => console.log(err));
        },

        deletePost(post) {
            axios.delete("http://www.example.com/posts",{
                params: {id: post.id}
            }).then(res => {
                if(res.status == '200') {
                    this.updatePosts(); // this will update array
                }
            }).catch(err => console.log(err));
        }
   }
}

</script>

当点击页面底部时,请记住将 current_page 值增加 1。


推荐阅读