Skip to main content

Quickstart: Vue.js

Introduction

This article will cover building a Quickstart Blog App using Vue.js and Altogic. The application will cover the following features:

  • Create blog post

  • List all blog posts

  • View single blog post on a separate page

You can reach out the demo here.

Altogic Designer

Create App

We can create an app with the Altogic Designer. To create an app via the Designer:

  1. Log in to Altogic with your credentials.

  2. Select New app.

  3. In the App name field, enter a name for the app.

  4. And click Next.

  1. Choose Blank App template, and click on Next.

  2. Click Create on the “Confirm & create” tab.

Here, you can customize your subdomain, but not necessarily to do, Altogic automatically creates one for you, which will be your envUrl. You don’t need to worry if you lost your envUrl; you can get it from the Environments view of Designer.

Getting the environment URL

After creating our app, we need envUrl and clientKey to access our app via Altogic Client Library to create a web application.

In order to get the clientKey we need to enter the app which we have created before and;

  1. Click on App Settings at the left-bottom of the designer.

  2. And click on Client library keys section.

Getting the Client Library Key

We can create new clientKey from that page, but thanks to Altogic for creating one clientKey automatically for us, so let’s copy the existing clientKey from the list.

Additionally, since we won’t use any authentication feature, we have to be able to send requests without session. We have to remove the enforcement of the sessions from the client.

  1. Click on the related client key.

  2. Untick the Enforce session checkbox

Create Blog Model

  1. Click on Models on the left sidebar.

  2. Click New on the right of the screen and select Model.

  3. Set model name as blogs

  4. Ensure that Enable timestamps is selected to store the creation date of the blog post.

  5. Click Next.

Altogic provides basic CRUD endpoints and services with the related model by default when you create a new model. Since we use Altogic Client Library, we won’t use these endpoints. Unselect all endpoints and click Create.

We created our first model ”blogs”. All we have to do is define model properties title and content. Since we created the blogs model, we should define the content property as rich text and the title as text.

  1. Click on the blogs model on the Models page

  2. Click on New Field on the right-top of the page.

  3. Select Text Field→ Text.

  4. Set model name title.

  5. Ensure that the Required field is selected.

  6. Click Create.

  1. Click on New Field on the right-top of the page.

  2. Select Text Field→ Rich Text.

  3. Set model name content.

  4. Click Create

We completed the database design and the model definition on Altogic. Let’s move on to the development of the frontend.

Frontend Development

Create Vue App

First we need to create a Vue app. Ensure that VueCLI is installed before the installation.

Open your terminal and paste the following script. The script will create altogic-vue-blog-app-tutorial Vue app.

vue create altogic-vue-blog-app-tutorial

It is time to install the necessary dependencies!

Installation of Altogic Client Library

Install the Altogic Client Library to our project by using NPM or Yarn by running the following command:

npm install altogic

Create a .env file in the root directory of your application to set environment variables of the app:

touch .env

Paste the following script to your .env file and replace YOUR-APPLICATION-ENV-URL and YOUR-APPLICATION-CLIENT-KEY with the envUrl and clientKey you copied before, then return to your terminal.

VUE_APP_ALTOGIC_ENV_URL=YOUR-APPLICATION-ENV-URL
VUE_APP_ALTOGIC_CLIENT_KEY=YOUR-APPLICATION-CLIENT-KEY

Next, create a file to use the Altogic services and client.

Go back to your root directory and follow the commands below:

cd src
mkdir helpers
cd helpers
touch altogic.js

altogic.js will be created in the /src/helpers directory. Open the file in your editor and paste the following.

import { createClient } from "altogic";

let envUrl = process.env.VUE_APP_ALTOGIC_ENV_URL;
let clientKey = process.env.VUE_APP_ALTOGIC_CLIENT_KEY;

const altogic = createClient(envUrl, clientKey);

export default altogic;

Installation of VueRouter

Since we need different pages for each blog posts and another route for listing all blog posts, we have to implement a route structure to our app. We will use vue-router in our app.

Open the root directory in the terminal and run the following script:

npm install vue-router

Installation of Tailwind CSS

We will use Tailwind CSS for styling the project. Run the following commands in the root directory.

npm install -D tailwindcss postcss autoprefixer

Below command will create tailwind.config.js file:

npx tailwindcss init -p

Open the tailwind.config.js in the editor and copy/paste following script to configure template paths:

module.exports = {
content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

Create a index.css file in src directory and add the following directives:

@tailwind base;
@tailwind components;
@tailwind utilities;

Open your main.js file and add the following script to the header of the file:

import "./index.css"

Components

Before moving on to the development of the components, you can delete the HelloWorld.vue component under the src folder came by default.

We will develop two single components:

  • BlogList: List all blog posts and create a blog post

  • SingleBlog: View single blog post details

We will create BlogList.vue and SingleBlog.vue files in the /src/components directory. Open the root directory in your project and paste the following script line by line.

cd src/components
touch SingleBlog.vue BlogList.vue

BlogList

We will list all the blog posts in this component. There is a form structure on the top of this component to create a new blog post.

Altogic Client Library provides us to create, get, update, delete, list any instance on the database by elementary functions. We will use create and get functions in our app:

  • altogic.db.model(<MODEL_NAME>).get(): Retrieves all instances from the related table

  • altogic.db.model(<MODEL_NAME>).object(<CREATED_INSTANCE>).create() Creates an instance on the database with the input data

We call the altogic.db.model("blogs").get() function inside the mounted() to fetch the blogs from the database when the component is rendered.

<template>
<div>
<div class="justify-center flex mb-5">
<div class="border rounded p-3 w-96 my-4 bg-white">
<!-- Form structure to get the created blog post data from the user.
When the form is submitted, createBlogPost() function will be triggered. -->
<form @submit="createBlogPost" class="text-left">
<div>
<label class="text-xs">Blog Title</label>

<div>
<input
class="border rounded mb-2 w-full text-sm p-1"
type="text"
v-model="title"
/>
</div>
</div>
<div>
<label class="text-xs">Blog Content</label>
<div>
<textarea
class="border rounded mb-2 w-full text-sm h-24"
type="text"
v-model="content"
/>
</div>
</div>
<div>
<button
type="submit"
class="text-sm bg-blue-600 p-1 rounded text-white w-full"
:disabled="title == ''"
>
Create Blog Post
</button>
</div>
</form>
</div>
</div>
<h2 class="text-center font-semibold">Blog Posts</h2>
<div class="grid grid-cols-3 m-3 px-12">
<!-- We will list blog post by mapping the blogs array state in here -->
<div
class="border rounded p-3 m-1 bg-white"
v-for="blog in blogs"
:key="blog._id"
>
<!-- Redirects user to the blog post's special page by clicking on it. -->
<router-link :to="`/blog/${blog._id}`">
<div class="text-sm truncate">{{ blog.title }}</div>
<div class="text-gray-400 text-sm truncate">
{{ blog.content }}
</div>
<div class="text-right text-xs my-1 text-gray-400 truncate">
{{ blog.createdAt }}
</div>
</router-link>
</div>
</div>
</div>
</template>

<script>
import altogic from "../helpers/altogic";
export default {
name: "BlogList",
data() {
return {
title: "",
content: "",
blogs: [],
};
},
methods: {
async createBlogPost(event) {
event.preventDefault();
// We can create an instance in the database by calling altogic.db.model().object().create() function
const result = await altogic.db.model("blogs").object().create({
title: this.title,
content: this.content,
});
// If we create an blog post instance in the database successfully, we update our blogs state by appending the new blog post.
if (!result.errors) {
this.blogs = [...this.blogs, result.data];
}
this.title = "";
this.content = "";
},
},
async mounted() {
const result = await altogic.db.model("blogs").get();
// It there are no error message set the blogs state with the retrieved data
if (!result.errors) {
this.blogs = result.data;
}
},
};
</script>

SingleBlog

SingleBlog component is the component where you can view a blog’s details such as blog content and creation date.

Each blog post has its own page in the /blog/:id route where id is the blog’s unique ID. We can reach the ID by this.$route.params.id inside the Vue component.

We retrieve the blog data with altogic.db.model("blogs").object(id).get() function in the mounted() hook.

<template>
<div class="text-left p-2 lg:mx-64">
<router-link class="text-xs text-blue-600" to="/">
Back to Blogs
</router-link>
<div class="text-sm mt-5 text-center" v-if="blog">
<h2 class="text-xl my-2">{{ blog.title }}</h2>
<div class="text-sm text-gray-600">
<div v-html="blog.content"></div>
</div>
<div class="mt-3 text-xs text-gray-500">{{ blog.createdAt }}</div>
</div>
</div>
</template>

<script>
import altogic from "../helpers/altogic";
export default {
name: "SingleBlog",
data() {
return {
blog: null,
};
},
async mounted() {
// Fetch the blog data after mounted
const result = await altogic.db
.model("blogs")
.object(this.$route.params.id)
.get();
if (!result.errors) {
this.blog = result.data;
}
},
};
</script>

Router & Routes

Now we have to define our routes to our app. Create a router.js file inside src directory.

We will need two different route type in our app:

  • Listing blog posts view

  • Single blog post view

We will specify our routes with related components in router.js file

import VueRouter from "vue-router";

const router = new VueRouter({
routes: [
{
path: "/",
name: "index",
component: () => import("@/components/BlogList.vue"),
},
{
path: "/blog/:id",
name: "blog",
component: () => import("@/components/SingleBlog.vue"),
},
],
mode: "history",
});

export default router;

Now, it only remains the passing the router object defined in router.js file to the app object rendered in main.js file and defining the router views to our App component.

Open your main.js file and paste the following code snippet:

import Vue from "vue";
import App from "./App.vue";
import "./index.css";
import router from "./router";
import VueRouter from "vue-router";

Vue.config.productionTip = false;
Vue.use(VueRouter);

new Vue({
render: (h) => h(App),
router,
}).$mount("#app");

Open your App.vue file and copy & paste the following code snippet:

<template>
<div id="app" class="bg-slate-50 min-h-screen">
<router-view></router-view>
</div>
</template>

<script>
export default {
name: "App",
};
</script>

Now, you can run your project by typing npm run serve on the root directory of the project! You can reach out the source code of this app here.