How To Build A Simple Single Page Application Using Vue 2 (Part 1)

Ogundipe Samuel Ayo

Today, we will be learning how to build a single page application using Vue.

Vue.js is a library for building interactive web interfaces. It provides data-reactive components with a simple and flexible API.

For the purpose of this tutorial, the term Vue refers to Vue 2.X versions unless stated otherwise.

What We Will Build

Let's take a quick view at what we would be building:

This tutorial, however, hopes that you do understand:

1.) The basics of Vue. 2.) How to create Vue Components.


Getting started with the Vue CLI

To get started easily, and also skip the process of configuring webpack for the compilation from ES6 to ES5, we would use the vue cli. If you do not have the Vue cli installed, we can install it by doing the following.

sudo npm install -g vue-cli

After installing the vue-cli, it is now time for us to create a vue project. To do that, we run the following command.

Note: For the purpose of this tutorial, while running the command below, I chose no when asked for code linting.

Code linting would make sure that codes are properly indented, as well as empty spaces are not left. But I like to leave empty spaces in my code, to keep it organized.

vue init webpack spa

In the above command, we would notice two strange words which are webpack and spa.

Webpack in this command refers to the name of the template we would like to scaffold, as the vue-cli helps us to scaffold templates. There are different templates to use, for more information on that, you can visit here.

Spa in this command refers to the folder name for our application which would be created. After running the above code, we would need to change directory into our application, and install the modules:

//change directory to the folder
  cd spa
//install all required npm modules
  npm install
//run the development server
  npm run dev

After running the above commands, if we go to http://localhost:8080, we should see this:


Installing and configuring the Vue router

Now we are set up and ready to start our single page application. However, we have one more dependency to install, named vue-router.

Vue-router is the official router for Vue. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:

  1. Nested route/view mapping
  2. Modular, component-based router configuration
  3. Route params, query, wildcards
  4. View transition effects powered by Vue.js' transition system
  5. Fine-grained navigation control
  6. Links with automatic active CSS classes
  7. HTML5 history mode or hash mode, with auto-fallback in IE9
  8. Customizable Scroll Behavior

If you have done angular before, or you have any knowledge of angular, the vue-router is synonymous to the angular router or if you have any knowledge of react, it is also synonymous to the react-router.

The main reason for which we use vue-router is because it allows us to switch between pages/routes without our page been refreshed/reloaded.

That been said, let us look at how we can install it.

We can install it by running the following command.

npm install vue-router --save

Now let's head into our src/main.js to configure the application to use the router.

Copy and replace the contents of src/main.js to this:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
//import the vue instance
import Vue from 'vue'
//import the App component
import App from './App'
//import the vue router
import VueRouter from 'vue-router'
//tell vue to use the router
Vue.use(VueRouter)
//define your routes
const routes = []

// Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
  routes, // short for routes: routes
  mode: 'history'
})
//instatinat the vue instance
new Vue({
//define the selector for the root component
  el: '#app',
  //pass the template to the root component
  template: '<App/>',
  //declare components that the root component can access
  components: { App },
  //pass in the router to the Vue instance
  router
}).$mount('#app')//mount the router on the app

Let's take a fast look at the above code. We imported the Vue class from our node modules, we then also imported the App component.

The app component is the default component created by the vue cli. We, however, import it to be used as our root component.

After this, we then import the Vue router, and then tell the Vue class that it can use the vue router by doing vue.use(vuerouter).

In the next line, we define a constant called routes and for now, we set it to an empty array. However, the routes are supposed to be an array of objects, where each object represent a path. We, however, would see more to this very soon.

The next thing we do is to create our router. An instance of the Vue router, which we pass in two parameters to it.

The first parameter being the routes array we have declared above, and the other one, being the mode. The mode parameter, however, was passed so as to prevent our URL'S from having the # sign in them, which has also proven not to be good for SEO purposes when URL'S have the # in them.

After all of this, we create a new Vue instance, in which we pass in the details of our root component, as well as declare the mounting point of the router.

At this point, if we re-serve our application, we would notice that nothing seems to have changed. However, we now have our router set up.

The next step to take now would be to replace the content of our App component with the router outlet, where every component matched with our view will be rendered, using the <router-view></router-view> tags.

Now open your src/App.vue file and replace it with the following content:

<template>
  <div id="app">
  <!-- the router outlet, where all matched components would ber viewed -->
  <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app',
}
</script>
<!-- styling for the component -->
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

If we look at the above code, we would notice some differences from the code which was auto-generated there, these differences include:

  1. The router-view tag that was placed inside the template, for rendering views.
  2. The removal of the import statement for the hello component.
  3. The removal of the component block in the script tag itself.

The removed components were removed because it wasn't needed anymore, but the most important one is the router view tag which was added, as discussed above.

At this point, if we reload our app, we would get an empty page.


Setting up our routes

Now let's go ahead to add the hello component as our component for the home page and also add the path to our routes array.

Open up your main.js file, and replace the block that holds the routes constant with this:

//import the hello component
import Hello from './components/Hello'
//define your routes
const routes = [
//define the root url of the application.
{ path: '/', component: Hello }
]

If we look at the above code, we have imported the hello component that comes by default and assigned the path as the component that handles our root path, and as such, if we reload our page, we should see this now:

We would notice from the image above that the logo of Vue, does not appear again, that is because we had removed the image when we were replacing the content of App component.

Now let's define one more route, and as such, let's create one more component.

So create a file inside the src/components folder called About.vue and let's place the following into it.

<template>
  <div id="about">
  When you have a great story about how your product or service was built to change lives, share it. The "About Us" page is a great place for it to live, too. Good stories humanize your brand, providing context and meaning for your product. What’s more, good stories are sticky -- which means people are more likely to connect with them and pass them on.
  </div>
</template>

<script>
export default {
  name: 'about'
}
</script>
<!-- styling for the component -->
<style>
#about {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Now let's look at the above component. The component holds some text inside the template, which would be rendered once we get to the link of the about page. However, we would still need to add the new component and path to our routes before it can be viewed.

To do that, open your main.js and replace the routes constant block with the following:

//import the hello component
import Hello from './components/Hello'
//import the about component
import About from './components/About'
//define your routes
const routes = [
//route for the home route of the web page
{ path: '/', component: Hello },
//route for the about route of the web page
{ path: '/about', component: About }
]

In the above code, The only difference now is that we have imported the about component, and also added the route to our path.

If we now navigate to http://localhost:8080/about, we would see that our about text is being rendered.


Using the router links

However, this is not what we want to do. The aim of a single page application is such that the page does not reload again. For us to accomplish this, we would need to use the <router-link></router-link> tag.

Let us open our App.vue file, and then add a router link to it. so before the declaration of our <router-view></router-view> in the component, let's add two router links:

<router-link v-bind:to="'/'">Home</router-link>
<router-link v-bind:to="'/about'">About</router-link>

What the above code does is that it would create two anchor tags for us, and do the dynamic routing, such that the page doesn't reload.

If you reload your app, we would notice two new links added to it. On click of those links, the view is changed, and the page does not reload.

At this point, your application should look like what we have below.

In the image below, notice the two links placed above, and that the page does not reload.


Conclusion

Viola, This is how to create a simple single page application.

However, you can make it more complex by:

  1. Adding more Routes
  2. Passing parameters alongside the routes
  3. Using route guards to protect routes where non-authenticated users can visit.

In the next part of this tutorial, we would visit passing of parameters, as well as using route guards to guard your Application.

Ogundipe Samuel Ayo

7 posts

Self Taught Software Developer. Software Developer At Crust Resources Conversant with Php (Codeigniter and Laravel), Python (Flask and Django), C# (WPF), Javacript (Vue, Angular, React-native, Node.js (Adonis.js, Express) ). Can Use the Mean Stack, But never used it For anything Serious