Building a PWA vuejs app with wordpress API – Part 6

Conditional rendering.

Our category system is a bit basic right now – it doesnt check to see which categories actuall have posts (and which categories have child-categories), so in this post we will be adding these checks – checking if the categories have sub-categories, and checking if they have posts

We start by adding a call in Category.vue component

  data(){
    return {
      post: []
    }
  },
  mounted(){
    axios.get('https://jonathansblog.co.uk/wp-json/wp/v2/posts?categories=' + this.category.id)
    .then(response => {
      this.post = response.data
      console.log(response.data)
    })  
  }

This will query our endpoint and return data for posts blonging to the current category. We combine this with a v-if statement:

<router-link v-if="post.length > 0" class="btn btn-success btn-block" v-bind:to="'/category/' + category.id">View Posts</router-link>

This will only render the button when we have actual posts contained in the category. Expanding on the same concept, we can conditionally show the ‘view subcategories button’

axios.get('https://jonathansblog.co.uk/wp-json/wp/v2/categories?per_page=100&parent=' + this.category.id)
.then(response => {
  this.cat = response.data
  console.log(response.cat)
}) 

<router-link v-if="cat.length > 0" class="btn btn-success btn-block" v-bind:to="'/category_list/' + category.id">View Sub Categories</router-link>

Adding it all together, our ‘categories’ component looks like this:

<template>
  <div>
    <div class="container">
      <div class="row">
        <div class="col-12">
          <h1 v-html="category.name"></h1>
          <router-link v-if="post.length > 0" class="btn btn-success btn-block" v-bind:to="'/category/' + category.id">View Posts</router-link>
          <router-link v-if="cat.length > 0" class="btn btn-success btn-block" v-bind:to="'/category_list/' + category.id">View Sub Categories</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Category',
  props: ['category'],
  data(){
    return {
      post: [],
      cat: []
    }
  },
  mounted(){
    axios.get('https://jonathansblog.co.uk/wp-json/wp/v2/posts?categories=' + this.category.id)
    .then(response => {
      this.post = response.data
      console.log(response.data)
    }),
     axios.get('https://jonathansblog.co.uk/wp-json/wp/v2/categories?per_page=100&parent=' + this.category.id)
    .then(response => {
      this.cat = response.data
      console.log(response.cat)
    })  
  }
}
</script>

<style scoped>
h1 {
  margin: 40px 0 0;
}
</style>
Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Adding Cordova to an existing Vue App

Leave a Reply