How to Create a Headless WordPress Site with Vue.js

Table Of Content

Introduction

There’s just one quote I can think about when it comes to WordPress and that is “Veni, Vidi, Vici” which means “saw, came, and conquered” WordPress just saw the potential of the market, and therefore it came with a vision and conquered half of the market. There are currently 1.3 billion websites and around 455 million websites are using WordPress. Yes, I am not lying, it’s 455 with six zeros behind it. 

And now with the help of headless WordPress, you can keep both the frontend and backend different, and due to this the developers and the editors both are satisfied because you can use Angular or React or Vue or any other framework in the frontend while you can use WordPress in the backend. So that the content managers can change the content as per their convenience in WordPress because of the ease of use while the developers can play with the codes in the frontend.

Here we are going to talk about how to build a headless WordPress website with Vue.Js? and why Vue.Js you ask? Because big enterprises like Facebook, Netflix, Trivago, Grammarly, Gitlab, Behance, BMW, Upwork, Apple, and 9Gag use Vue.Js as their front-end development technology. Now, do I need to give you more reasons why VueJs?

So let’s start the article.

What is Headless WordPress?

If you have been in the market of CMS for a long time you would know that WordPress is known as a ‘monolithic’ CMS. That means you would have a robust backend where you can go and do content creation as well as organize the content, and it is still designed to focus on the front-end experience. With the help of WordPress, you can also embed display functionality using themes and plugins and therefore the front and back ends are intertwined with each other.

Although WordPress can be used as a great content management system, you can use the excellent functionality WordPress has to offer and effectively execute it, which leaves a fast, lightweight headless content management system. You can utilize the REST API provided by WordPress to extend your content management beyond your theme. 

When you use Headless WordPress you will be able to use the WordPress platform’s back-end functionality, but it will turn into a reactive system, which means the content will be automatically resized to the screen size the website is being viewed on, and it is clearly different from the current WordPress which is more proactive it pushes or delivers content to mostly browser-based sites.

Now, this is the easy way to know what a Headless WordPress is, let’s dive into it in some technical ways.

With the help of Rest API which allows the developers to interact with cross-technology interfaces as long as both of them are speaking the JSON language. The data that comes out with the help of Rest API is in JSON format, and JSON is the most loved format known by almost every web technology. JSON is a text-based representation of JavaScript objects which contains data in key-value pairs.

"names": [
     {
       "id": 0,
       "name": "John Doe"
     },
     {
       "id": 1,
       "name": "Richard Lindley"
     },
     {
       "id": 2,
       "name": "Jack Moore"
     }
   ],

Today, I will demonstrate the power of WordPress Rest API by using it with Vue.js and WordPress as a headless CMS for my basic web application.

The Benefits of Using Headless WordPress CMS

The fact that WordPress is an open-source platform takes away half of your concerns since it gives you great flexibility to design any type of website. And now due to Headless, you are able to create the front end of your web application with any web technology which you desire to use and manage the content of your website using the most loved CMS.

When your website starts to grow you might feel an urgency to create a blog feature because you want people to learn about your product or the service you provide but your web app is built with Vue.js or React. You have to do coding to build it, but that’s where you can take the help of WordPress Rest API and manage the content.

How to Set Up a WordPress Site with Vue.js

Set up WordPress website for vuejs 1024x397 1

Firstly what we have to do is create a WordPress site, because it will be our main source as it will act as a data source for whatever front-end technologies we are going to use. Rest API will be turned on by default, and if you desire to restrict the Rest API access then what you gotta do is you can use Basic-Auth or Oauth2 authentication method.

Go to Settings → Permalinks and select either Post name or Custom Structure.

25230535 e96b0f9972bca6f3f1a519aeb102f8f5 1024x506 1

And now that we are working with API calls, you need to download the chrome extension for Postman. And now that you have downloaded the Postman extension, open it and enter the URL in the format given below. 

https://example.com/wp-json/wp/v2/posts

The above URL will fetch the posts data inside your WordPress site.

25246400 1adad24a479012b7fe0826fdafa9d450 1024x542 1

Getting Started with Vue.js

Get started with vue js 1024x397 1

What is Vue.Js?

The framework, created by Evan You and released in 2014, was a direct result of his experience working with AngularJS at Google. You decided to take some of the bits and pieces that he liked about AngularJS, and combine them together to create a lightweight framework that is entirely new.

Vue is a framework for developing progressive user interfaces. In contrast to other monolithic frameworks, Vue is purpose-built to be slowly adopted. The core library is entirely dedicated to the view layer, making it simple to combine with other libraries or existing projects. On the other hand, when combined with contemporary technology and accompanying libraries, Vue is perfectly capable of powering sophisticated Single-Page Applications.

Setting up Vue.js App

In this article, we will be discussing how to build a blog site. All the backend content management of the project will be done using headless WordPress.

To build Vue.js apps, you need to have the following pre-requisites installed on your computer.

  • NodeJS & NPM
  • Vue CLI
  • Text Editor such as Sublime or Visual Studio Code
  • Git for version controlling (Optional)

After setting up the environment, open the command line and run the following code to create the project with the Vue.js app.

vue create blog

Once the project is created, run the following command and you will be able to see vue js app project output on http://localhost:8080

npm run serve

check out this documentation to walk you through the process of creating a project.

Finally, you should open the Vue 3 codebase in any code editor that you feel comfortable with. In this tutorial, we will use VSCode, and this is where we’re going to get into coding.

Copy the code below to your App.vue file:

<template>
  <div>
    <ul v-for="post in posts" v-bind:key="post.id">
      <li>{{ post.title.rendered }}</li>
      <p>{{ post.content.rendered }}</p>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: [],
    };
  },

  methods: {
    async getData() {
      try {
        let response = await 
        fetch("https://example.com/wp-json/wp/v2/posts");
        this.posts = await response.json();
      } catch (error) {
        console.log(error);
      }
    },
  },

  created() {
    this.getData();
  },
};
</script>

The above block of code in the methods property will be explained line by line.

async getData(){

And with this, you will create a function named getData(). In this function, the API will be called. The async keyword is prepended on the getData function to show that the function will make use of promises and we’ll be using it to await to pause the execution of the function until the promise is resolved. 

try {
  let response = await 
fetch('https://example.com/wp-json/wp/v2/posts');

try property defines a block of code to be tested for errors as the code is executed. In the block of code let response = await fetch('https://example.com/wp-json/wp/v2/posts');, a fetch method is used to get data from the URL.

await is prepended to the request because the fetch function will return a promise. The data returned from the API after the promise is resolved and will be stored in the variable response.

this.posts = await response.json();

And the data which we will receive from the request is then saved to the posts array which is created in the data property. 

catch (error) {
    console.log(error);
}

If any error occurs during the execution, the error will be caught and logged in the console.

After requesting data from the API, you will need to call it on a lifecycle hook. Here we will use the created() lifecycle hook, this is because we will be able to retrieve sensitive data and events that are active with the created hook.

created() {
    this.getData();
  },

We can now display the data in the template by looping through the posts using the v-for directive.

<div v-for="post in posts v-bind":key="post.id">
  <h2>{{post.title.rendered}}</h2>
  <p>{{post.content.rendered}}</p>
</div>

Summary

That concludes our discussion! All the advantages of a rich content editing system like WordPress, combined with the performance and security advantages of Vue.Js. Now you may detach content creation from your development stack and create your own app using a current JavaScript framework and the robust ecosystem! As I continue to use WordPress as a headless CMS, I find that it becomes more and more enjoyable each time I do so! It is always a pleasure to develop with a framework like vue.js.

Frontend in Vue and backend in WordPress will provide you with all the necessary functionalities you require for your website to grow. Headless WordPress is here to stay and now with the new upgrade of Vue, you can not only create enterprise-level websites but also small-scale websites for your business. Hire experienced developers from – a leading Vue. Js Development company, which helps you to provide the most suitable and comprehensive solutions for mobile and web app development using the Vue.js framework. Also, be sure to learn more about Best Vue UI Component Libraries.

author
Vish Shah is Technical Consultant at WPWeb Infotech since 2015. He has vast experience in working with various industries across the globe. He writes about the latest web development technologies and shares his thoughts regularly.

Leave a comment