【问题标题】:Laravel and vue infinite loader and pagination problemLaravel 和 vue 无限加载器和分页问题
【发布时间】:2020-06-12 19:14:03
【问题描述】:

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

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

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

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

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

但是如何解决呢? 这个问题有解决办法吗

【问题讨论】:

    标签: laravel api vue.js pagination infinite-scroll


    【解决方案1】:

    我认为最好的解决方案是在每次删除请求后更新 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。

    【讨论】:

    • 谢谢您,但由于您的解决方案,我们仍然逃脱了帖子。我已经在The Problem 部分解释了更多问题。 id 为 4 的帖子永远不会出现。
    猜你喜欢
    • 2018-07-30
    • 2021-12-05
    • 2012-02-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2020-08-10
    • 2017-09-03
    相关资源
    最近更新 更多