通过REST API -WORDPRESS和VUEJS按类别获取帖子



我正在尝试通过WordPress Restful API获取一些帖子数据。到目前为止,我所取得的成就是:

  1. 加载应用程序时,获取帖子的第一页。
  2. 然后,如果用户单击"加载更多帖子",则帖子的另一页被提取,直到没有更多的帖子可以显示

首先,我在main.js文件中创建此功能:

Array.prototype.next = function*(){
  for(let item of this){
    yield item
  }
}

然后在app.vue中,我有:

created(){
    this.$store.dispatch('setCategories') //grab posts categories
      .then(resolve=> this.$store.dispatch('setPostsCount')) //grab the number of post pages and the total number of posts
        .then(resolve=>this.$store.dispatch('loadPosts')) load the first page of posts
          .catch(err => console.log(err))
  }

这是商店模块post.js:

  import axios from 'axios'
const postsRequest = axios.create({
    baseURL: 'https://wordpress-site/wp-json/wp/v2/posts'
  })



const state = {
    posts:[],
    filteredPosts:[],
    totalPages:null,
    totalPosts:null
}

const getters = {
    getPosts(state){
        return  state.posts
    },
    getFilteredPosts(state){
        return state.filteredPosts
    },
    getAllPostsPages(state){
        return state.totalPages
    },
    getAllPostsNumber(state){
        return state.totalPosts
    },
    getNextPage(state,getters){
        return getters.getAllPostsPages.next()
    }
}

const mutations = {
    'SET_POSTS_COUNT'(state,headers){
        state.totalPages = [...Array(parseInt(headers['x-wp-totalpages'])).keys()].map(page => page+1),
        state.totalPosts = parseInt(headers['x-wp-total']) //[...Array(parseInt(headers['x-wp-total'])).keys()]
    },
    'LOAD_POSTS'(state,posts){
        for(let post of posts){
            state.posts.push(post)
        }
        console.log(state.posts.length)   
    },
    'FILTER_BY_CATEGORY'(state,posts){
        state.filteredPosts = []
        state.filteredPosts = posts
    },
    'EMPTY_FILTERED_POSTS'(state){
        state.filteredPosts = []
    }
}

const actions = {
    setPostsCount({commit}){
        return new Promise((resolve,reject)=>{
            postsRequest.get().then(response => {
                commit('SET_POSTS_COUNT',response.headers)
                resolve()
            })  
        })
    },
    loadPosts({commit,getters}){
        let nextPage = getters.getNextPage.next()
        if(!nextPage.done){
            postsRequest.get(this.baseURL,{
                params:{
                    page: nextPage.value
                }
            }).then(response=> {
                commit('LOAD_POSTS',response.data)
            })
            .catch(err => console.log(err))
        }
    },
    loadPostsByCategory({commit,getters},index){
            postsRequest.get(this.baseURL,{
                params:{
                    categories:index
                }
            }).then(response => commit('FILTER_BY_CATEGORY',response.data))
                .catch(err => console.log(err))
    },
    loadPostsByCat({commit,getters},category){
        ...
    }
}
export default {
    state,
    getters,
    actions,
    mutations
  }

这是我显示帖子的组件:

 <template>
    <div class="gy-read">
        <div @click="emptyFilteredPosts()">all</div>
        <div style="display:inline-block;margin-left:20px" v-for="category in categories" :key="category.id">
            <h3 @click="searchByCategory(category.index)">{{category.name}}</h3>
        </div>
        <div v-for="post in posts" :key="post.id">
            <h2>{{post.title.rendered}}</h2>
            <h4>{{post.date}}</h4>
            <h4>{{post.categories}}</h4>
        </div>
        <div>
            <button v-if="!currentCategory" @click="loadMorePosts()">load more</button>
            <button v-else @click="loadMorePostsByCat()">load more cat</button>
        </div>

    </div>
</template>
<script>
export default {
    data(){
        return{
            currentCategory:null,
        }
    },
 computed:{
     posts(){
         return this.$store.getters.getFilteredPosts.length ? this.$store.getters.getFilteredPosts : this.$store.getters.getPosts
     },
     categories(){
         return this.$store.getters.getCategories //this simply create an array of category index
     },
 },
 methods:{
     loadMorePosts(){
        this.$store.dispatch('loadPosts')
     },
     loadMorePostsByCat(){
         this.$store.dispatch('loadPostsByCat',this.currentCategory)
     },
     searchByCategory(index){
        this.currentCategory = index;
        this.$store.dispatch('loadPostsByCategory',index)
     },
     emptyFilteredPosts(){
         this.$store.commit('EMPTY_FILTERED_POSTS');
         this.currentCategory = null;
     }
 }
}
</script>
<style lang="scss">
    .gy-read{
        margin-top:150px;
    }
</style>

现在我被卡住了:一旦用户单击类别,state.posts列表就会替换为state.filteredposts列表,其中包含通过REST API访问类别的前10个帖子(请参阅searchByCategory方法(。

现在,我希望load more按钮仅使用具有相同类别的帖子升级帖子列表,除了已经存在的帖子。

这是可能的,还是我必须重新考虑我的实现?

此实施仅适用于帖子总量,无论类别是什么。

我无法修改PHP,我只需要与Vue一起工作。

谢谢!

好的,我以这种方式解决了。正如Sphinx所建议的那样,当类别更改时,我将帖子的数组重置为0,并提出另一个请求,还使用已经存在的帖子数量的偏移基础。似乎有效:

组件:

<template>
    <div class="gy-read">
        <div class="category">
            <div @click="currentCategory='all'">all</div>
            <div v-for="category in categories" :key="category.id">
                <h3 @click="currentCategory = category.index">{{category.name}}</h3>
            </div>
        </div>
        <div class="card__container">
            <router-link tag='div' class="card" :to="{name:'article', params: {slug: post.slug, post:post}}" v-for="post in posts" :key="post.id">
            <div :style="{ backgroundImage: 'url(' + post.better_featured_image.source_url+ ')' }" class="card__img"></div>
            <div class="card__content">
                <h2>{{post.title.rendered}}</h2>
                <span v-for="cat in post.categories" :key="cat">{{ cat}}</span>
            </div>  
        </router-link>
        </div>
        <div class="load">
            <button ref="button" v-if="posts.length" @click="loadMorePosts()">load more</button>
        </div>

    </div>
</template>
<script>
export default {
    data(){
        return{
            currentCategory:null,
        }
    },
    created(){
    },
 computed:{
     posts(){
         return this.$store.getters.getPosts
     },
     categories(){
         return this.$store.getters.getCategories
     }
 },
 watch:{
     currentCategory: function(cat){
         console.log(cat)
         this.$store.commit('RESET_POSTS')
         this.loadMorePosts()
     }
 },
 methods:{
     loadMorePosts(){
        this.$store.dispatch('loadPosts',this.currentCategory)
     },
 }
}
</script>

商店:

import axios from 'axios'

const state = {
    posts:[]
}

const getters = {
    getPosts(state){
        return  state.posts
    },
}
const mutations = {
    'LOAD_POSTS'(state,posts){
        for(let post of posts){
            state.posts.push(post)
        }  
    },
    'RESET_POSTS'(state){
        state.posts = []
    },
}

const actions = {
    loadPosts({commit,getters},category){
            axios.get('/posts',{
                params:{
                    categories: category === 'all' ? null : category,
                    offset: getters.getPosts.length
                }
            }).then(response=> {
                if(response.data.length){
                    console.log(response.data)
                    commit('LOAD_POSTS',response.data)
                }else{
                    //this._vm.$emit('noMorePosts',null)
                }
            })
            .catch(err => console.log(err))

    }
}
export default {
    state,
    getters,
    actions,
    mutations
  }

app.vue创建的钩子:

created(){
    this.$store.dispatch('setCategories')
        .then(resolve=>this.$store.dispatch('loadPosts','all'))
          .catch(err => console.log(err))
  }

最新更新