Create Static Pages – VueJS WordPress Theme

in WordPress Theme

In the last tutorial we setup routes and components for our blog posts, we did this with dynamic routes. In this tutorial, we're going to create the routes and VueJS components for static pages.

As these are static pages the routes should be static too allowing us to define the exact routes for the pages.

Inside the route file located in /vue-wordpress-theme/src/router/index.js you need to add your static pages to the top of the route file.

{
      name: 'About',
      path: '/about',
      component: Page
    },

    {
      name: 'Contact',
      path: '/contactform',
      component: Page
    },

We now have routes for /about and /contactform that will display the Page component which we can create later.

The Page component is the same as the Post component the only difference is the API URL we call to search for pages instead of posts. To learn about how to build the post component you can view the tutorial with this link.

Page Component

Within the template tag of the Page Component we have the single-post component created in the previous tutorial, this is used to display the full content of the Page. All we have to do is pass in the page data into this component as a prop.

<template>
    <single-post v-bind:post="post"></single-post>
</template>

The rest of the component is the same as the post component the only difference is the URL to the WordPress REST API to search for pages.

var path = this.$route.path
axios.get(process.env.API_URL + '/wp-json/wp/v2/pages/?slug=' + path.replace(/^\/|\/$/g, ''))

Below is the full code for the Page component.

<template>
    <single-post v-bind:post="post"></single-post>
</template>

<script>
import axios from 'axios'
import SinglePost from '../global/SinglePost.vue'

export default{
  name: 'Page',
  data () {
    return {
      title: '',
      post: []
    }
  },

  created () {
    this.getPost()
    document.title = this.title
  },

  methods: {
    getPost () {
      var path = this.$route.path
      axios.get(process.env.API_URL + '/wp-json/wp/v2/pages/?slug=' + path.replace(/^\/|\/$/g, ''))
      .then(response => {
        this.post = response.data[0]

        if (this.post === undefined) {
          this.$router.push({name: 'NotFound'})
        }
      })
      .catch(e => {
        console.log(e)
      })
    }
  },

  components: {
    'single-post': SinglePost
  }
}
</script>

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email