Build a modern and efficient blog platform: the perfect combination of Vue.js and GraphCMS
Core points:
This guide will guide you how to build a modern blog website using Vue.js and GraphCMS (a headless CMS platform).
If you want to quickly start a blog today, I suggest you use WordPress directly.
But what if you are a media giant and want to deliver your content to multiple devices as fast as possible? You may also need to integrate your content with advertising and other third-party services. You can do this with WordPress, but you will encounter some problems with this platform.
In browser loading tests, JavaScript performs better than PHP. In addition, modern JavaScript and its ecosystem provide a more pleasant development experience in rapidly building new web experiences.
Want to learn Vue.js from scratch? This article is excerpted from our advanced library. Join SitePoint Premium now to get a complete collection of Vue books covering basics, projects, tips, and tools for just $9 per month.
So the number of headless CMS solutions (which is just the backend used to manage content) has grown. With this approach, developers can focus on building fast and interactive front-ends using their chosen JavaScript framework. Customizing a JavaScript-based front-end is much easier than changing a WordPress website.
The difference between GraphCMS and most headless CMS platforms is that it serves content instead of REST, but rather through GraphQL. This new technology is better than REST because it allows us to build queries that involve data belonging to multiple models in one request.
Consider the following model pattern:
Article
Comments
The above model has a one-to-many (article to comment). Let's see how to get a single article record with all link comment records attached.
If the data is in a relational database, you must construct an inefficient SQL statement, or construct two SQL statements to obtain the data cleanly. If the data is stored in a NoSQL database, you can easily get the data for you using a modern ORM like Vuex ORM, as shown below:
const post = Post.query() .with('comments') .find(1);
Very simple! You can easily pass this data to the target client via REST. But the problem is: whenever the client's data requirements change, you will be forced to return to your backend code to update your existing API endpoint, or create a new endpoint that provides the required dataset. This back and forth process is both laborious and repetitive.
If at the client level, you can just request the data you need without you doing the extra work, the backend will provide you with the data? Well, that's what GraphQL is for.
Before we get started, I would like to point out that this guide is for intermediate to advanced users. I won't explain the basics, but instead show you how to quickly build a Vue.js blog using GraphCMS as a backend. You need to be proficient in the following areas:
This is everything you need to know to start this tutorial. Also, the background knowledge of using REST will be very useful as I will quote it often. If you want to review it, this post might help: "REST 2.0 is here, its name is GraphQL".
We will build a very simple blog application with a basic comment system. Here are the links that can be accessed to view completed projects:
Note that read-only tokens are used in the demo, so the comment system will not work. You need to provide your OPEN permission token and endpoint as described in this tutorial to make it work.
Go to the GraphCMS website and click the "Start Build for Free" button. You will be taken to their registration page.
Register using your preferred method. After completing the account authentication and verification process, you should be able to access the main dashboard.
In the example above, I have created a project called "BlogDB". Continue to create a new project and name it as you like. After entering a name, you can leave the remaining fields as default values. Click to create and you will enter their project plan.
In this tutorial, select the free developer plan and click to continue . You will enter the dashboard of the project as shown below:
Go to ModeTab. We will create the following models, each with the following fields:
Category
Article
Comments
Create a model using Create a model button. On the right side, you should find a hidden panel for fields that can be activated by clicking the field button. Drag and drop the appropriate field type onto the model's panel. You will see a form to fill in the properties of the field. Note that there is a pink button at the bottom marked Advanced. Clicking it will expand the panel, giving you more field properties that can be enabled.
Next, you need to add the relationship between models as follows:
Define this relationship using the reference field. You can add this field on either side; GraphCMS will automatically create opposite relationship fields in the referenced model. After completing the model definition, you should have the following content:
You have now completed the first part. Now let's provide some data for our model.
To add content to the model, you can simply click the Content tab in the project dashboard where you can create new records for each model. However, if you find this to be a slow approach, you'll be happy to know that I've created a GraphCMS migration tool that can copy data from CSV files and upload it to your GraphCMS database. You can find the project in this GitHub repository. To get started with the project, simply download it to your workspace as follows:
const post = Post.query() .with('comments') .find(1);
Next, you need to get the API endpoint and token for your GraphCMS project from the Settings page of the dashboard. You need to create a new token. For permission levels, use OPEN as this will allow the tool to perform read and write operations on your GraphCMS database. Create a file named .env and place it in the root directory of the project:
git clone git@github.com:sitepoint-editors/graphcsms-data-migration.git cd graphcsms-data-migration npm install
Next, you may need to populate the CSV file in the data folder with your own data. Here are some sample data that have been used:
<code>ENDPOINT=<你的API端点> TOKEN=<你的OPEN权限令牌></code>
You can change the content as needed. Make sure not to touch the top row or you will change the field name. Note that for the category column I've used the pipeline | character as the delimiter.
To upload CSV data to your GraphCMS database, execute the following commands in the following order:
<code>// Categories.csv name Featured Food Fashion Beauty // Posts.csv title,slug,content,categories Food Post 1,food-post-1,Breeze through Thanksgiving by making this Instant Pot orange cranberry sauce,Food|Featured Food Post 2,food-post-2,This is my second food post,Food Food Post 3,food-post-3,This is my last and final food post,Food Fashion Post 1,fashion-post-1,This is truly my very first fashion post,Fashion|Featured Fashion Post 2,fashion-post-2,This is my second fashion post,Fashion Fashion Post 3,fashion-post-3,This is my last and final fashion post,Fashion Beauty Post 1,Beauty-post-1,This is truly my very first Beauty post,Beauty|Featured Beauty Post 2,Beauty-post-2,This is my second beauty post,Beauty</code>
Each script will print out the successfully uploaded records. The reason we upload categories first is to enable the article records to be successfully linked to existing category records.
If you want to clean your database, you can run the following command:
npm run categories npm run posts
This script will delete the contents of all models. You will receive a report indicating how many records each model has deleted.
I hope you find this tool very convenient. Return to the dashboard to confirm the number of articles and categories
The data has been uploaded successfully.
The backend is processed, let's start building our front-end blog interface.
As mentioned earlier, we will build a very simple blog application supported by the GraphCMS database backend. Start the terminal and navigate to your workspace.
If you haven't installed Vue CLI, install it now:
npm run reset
Then create a new project:
npm install -g @vue/cli
Select the manual selection function and select the following options:
After the project creation process is completed, change to the project directory and install the following dependencies:
vue create vue-graphcms
To set up Bootstrap-Vue in our project, just open src/main.js and add the following code:
npm install bootstrap-vue axios
Next, we need to start building the project structure. In the src/components folder, delete existing files and create these new files:
In the src/views folder, delete About.vue and create a new file named PostView.vue. As you can see from the demo, we will have several category pages, each showing a list of articles filtered by category. Technically, only one page will display a different list of articles based on the active route name. The PostList component will filter articles based on the current route.
Let's set up the route first. Open src/router.js and replace existing code with this code:
const post = Post.query() .with('comments') .find(1);
Now that we have the route, let's set up the navigation menu. Open src/App.vue and replace the existing code with this code:
git clone git@github.com:sitepoint-editors/graphcsms-data-migration.git cd graphcsms-data-migration npm install
This will add a navigation bar at the top of our website with links to our different categories.
Save the file and update the following files accordingly:
src/views/Home.vue
<code>ENDPOINT=<你的API端点> TOKEN=<你的OPEN权限令牌></code>
src/components/PostList.vue
<code>// Categories.csv name Featured Food Fashion Beauty // Posts.csv title,slug,content,categories Food Post 1,food-post-1,Breeze through Thanksgiving by making this Instant Pot orange cranberry sauce,Food|Featured Food Post 2,food-post-2,This is my second food post,Food Food Post 3,food-post-3,This is my last and final food post,Food Fashion Post 1,fashion-post-1,This is truly my very first fashion post,Fashion|Featured Fashion Post 2,fashion-post-2,This is my second fashion post,Fashion Fashion Post 3,fashion-post-3,This is my last and final fashion post,Fashion Beauty Post 1,Beauty-post-1,This is truly my very first Beauty post,Beauty|Featured Beauty Post 2,Beauty-post-2,This is my second beauty post,Beauty</code>
Note that in the PostList component, we use a custom observer to update our category data attributes based on the current URL.
We can now perform a quick test to confirm that the routing is working properly. Use the command npm run serve to start the Vue.js server. Open the browser at localhost:8080 and test each navigation link. The category property should output the same value we defined in the route name property.
Now that our routing code is working, let's see how to extract information from our GraphCMS backend. In the root of the project, create an env.local file and fill it with the values of the following fields:
npm run categories npm run posts
Note that the Vue.js single page application only loads custom environment variables starting with VUE_APP. You can find the API endpoints and tokens from your GraphCMS dashboard settings page. For tokens, make sure to create a token with OPEN permissions, as it will allow read and write operations. Next, create the file src/graphcms.js and copy the following code:
npm run reset
The auxiliary file we just created provides two main functions:
You can also use the API Explorer in the project dashboard to test these queries and mutations. To do this, copy the query or mutation from the above code and paste it into the top window of API Explorer. Enter any query variables in the window below and click the Play button. You should see the results in the new pane on the right.
This is a query example:
This is an example of variation:
Now, let's create an HTML template in src/components/PostList.vue which will display the post list in a concise way. We will also add axios code that will extract article data from our GraphCMS database:
const post = Post.query() .with('comments') .find(1);
Let's take a quick look at the main functions of the code:
After making these changes, you should now see the following view:
Make sure the top main navigation works as expected. Now let's deal with the Post component. It will have its own fetchPost() function, which will query by slug. If you want to know where the slug parameter comes from, let me remind you this piece of code we added in router.js:
git clone git@github.com:sitepoint-editors/graphcsms-data-migration.git cd graphcsms-data-migration npm install
This means that anything after /post/ in the URL can be used in the component as this.$route.params.slug.
The post component is the parent component of the CommentForm and CommentList components. Comment data will be passed as props from the article record to the CommentList component. Now let's insert the code of src/components/CommentList.vue:
<code>ENDPOINT=<你的API端点> TOKEN=<你的OPEN权限令牌></code>
Don't expect to see any results now unless you have manually entered comments through the GraphCMS dashboard. Let's add code to src/components/CommentForm.vue, which will enable users to add comments to blog posts:
<code>// Categories.csv name Featured Food Fashion Beauty // Posts.csv title,slug,content,categories Food Post 1,food-post-1,Breeze through Thanksgiving by making this Instant Pot orange cranberry sauce,Food|Featured Food Post 2,food-post-2,This is my second food post,Food Food Post 3,food-post-3,This is my last and final food post,Food Fashion Post 1,fashion-post-1,This is truly my very first fashion post,Fashion|Featured Fashion Post 2,fashion-post-2,This is my second fashion post,Fashion Fashion Post 3,fashion-post-3,This is my last and final fashion post,Fashion Beauty Post 1,Beauty-post-1,This is truly my very first Beauty post,Beauty|Featured Beauty Post 2,Beauty-post-2,This is my second beauty post,Beauty</code>
Now we have a basic comment form that is able to submit new comments to our GraphQL backend system. After saving a new comment, we will get the returned object and add it to the post.comments array. This should trigger the CommentList component to display newly added comments.
Now let's build the src/components/Post.vue component:
npm run categories npm run posts
Finally, here is the code for src/views/PostView.vue to bring everything together:
npm run reset
You should now see the view of the article. Pay attention to the end of the URL:slug:localhost:8080/post/fashion-post-1:
In the example above, I have added some comments to test for new features. Make sure you do the same.
I hope you have seen how easy it is to build a blog website using Vue.js and GraphQL. If you've been using plain PHP and MySQL, you'll write more code. Even with the PHP framework, you still need to write more code for simple blogging applications.
For the purposes of this tutorial, I have to keep it as simple as possible. You may notice that this blog project is far from reaching the easiest blog setup. We haven't solved many issues such as error handling, form validation, and caching. For the last part, I recommend the Apollo Client because it has a mechanism to cache the results of GraphQL query. Then of course, an author model and an appropriate comment system that supports authentication and message approval are needed.
If you prefer, please continue to improve this simple Vue.js GraphCMS blog.
Using headless CMS and Vue.js has many advantages. First, it provides a more flexible and efficient content management system. It separates the backend and the frontend, allowing developers to handle both ends independently. This separation also means that CMS can provide content to any platform, not just a website. Second, Vue.js is a progressive JavaScript framework that is easy to understand and integrates with existing projects. It provides a simple and flexible API that makes it the perfect match for headless CMS.
Integrating headless CMS with Vue.js involves several steps. First, you need to choose a headless CMS that supports API-based communication. Next, you need to set up your Vue.js project and install the necessary dependencies. You can then use the CMS's API to get the content and display it in your Vue.js application. Some CMS also offer SDKs or plugins to make this integration easier.
Yes, as long as the headless CMS supports API-based communication, you can use any headless CMS with Vue.js. This is because Vue.js is a front-end framework that communicates with the back-end (in this case CMS). Some popular headless CMSs you can use with Vue.js include Strapi, Sanity, and ButterCMS.
There are many projects using headless CMS and Vue.js. These projects range from blogs and e-commerce websites to full-fledged web applications. Some examples include a Vue.js document site using VuePress (a Vue-based static website generator), and a Storyblok site using Storyblok (a headless CMS) and Nuxt.js (a Vue.js framework).
Headless CMS can significantly improve the performance of Vue.js applications. By separating the backend and the frontend, it allows for more efficient content delivery. CMS can deliver only the necessary content, thereby reducing the amount of data that needs to be transmitted and processed. This can lead to faster page load times and a smoother user experience.
The difficulty of migrating from a traditional CMS to a headless CMS in a Vue.js project depends on the complexity of the project and the CMS used. However, most headless CMSs provide tools and documentation to aid in the migration process. Furthermore, since Vue.js is a flexible and modular framework, it can often adapt to such migrations without major changes to existing code.
Yes, headless CMS using Vue.js can support multiple languages. Many headless CMSs offer built-in multilingual support, allowing you to manage content in different languages. In terms of Vue.js, you can use libraries such as vue-i18n to handle internationalization.
Using headless CMS with Vue.js can be very safe. The separation of the backend and frontend adds an additional layer of security as it reduces the attack surface. Additionally, most headless CMSs offer powerful security features such as SSL encryption, user authentication, and access control. Vue.js also has built-in protections for common web vulnerabilities.
Yes, you can use headless CMS with Vue.js for mobile application development. Because the headless CMS provides content through the API, it can provide content to any platform, including mobile applications. Vue.js can be used to develop mobile applications using frameworks such as NativeScript or Weex.
The future development prospects of using headless CMS and Vue.js are broad. Both technologies are growing penetration rates and they are being used in more and more projects. The flexibility and efficiency of this combination, as well as performance advantages, make it a powerful choice for modern web development. As more developers become familiar with these technologies, we can expect to see more innovative uses and integrations.
The above is the detailed content of How to Build a Vue Front End for a Headless CMS. For more information, please follow other related articles on the PHP Chinese website!