Building a PWA vuejs app with wordpress API – Part 2

Continuing on fom Part1, where we made a (very) basic vuejs app to fetch data from a wordpress API, we will move on and in this tutorial we will set up some routes and create a basic ‘single’ page to show the content from a wordpress post

Tirst thing to do is to set a route – we will go with the wordpress naming and call this ‘post’

Open router.js and add a route for ‘post’

{
    path: '/post/:id',
    name: 'post',
    component: () => import ( /* webpackChunkName: "post" */ './views/Post.vue')
}

Create a vue file and add the following:

// Post.vue

<template>
  <div class="home">

    <img class="img-fluid" :src="post.jetpack_featured_media_url"> 
    <h1 v-html="post.title.rendered"></h1>
    <div v-html="post.content.rendered"></div>
  </div>
</template>

<script>
// @ is an alias to /src
import axios from 'axios'

export default {
  name: 'post',
  data(){
    return {
      post: []
    }
  },
    mounted(){
    axios.get('https://jonathansblog.co.uk/wp-json/wp/v2/posts/' + this.$route.params.id)
    .then(response => {
      this.post = response.data
      console.log(response.data)
    })
    
  }
}
</script>

We can link together with the following code in the PostSmall component:

<router-link class="btn btn-success" v-bind:to="'/post/' + post.id">View more</router-link>

This will take the ID from the fetched posts, and turn it to a link (which will get interpreted by the router and pass long to the post.vue file which will fetch that post form the WordPress API and render the content)

We now have a (very basic) app which will fetch our latest posts and display them

In part 3 we will be looking at categories (and adding lots of extras to the code we already have)

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Adding Cordova to an existing Vue App

Leave a Reply