This tutorial is out of date and no longer maintained.
Today, we will be learning how to build a single-page application using Vue.js.
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.
Let’s take a quick view of what we would be building:
This tutorial, however, hopes that you do understand:
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 that would be created.
After running the above code, we would need to change into the directory of our application:
- cd spa
Install the 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:
Now we are almost 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:
If you have done angular
before, or you have any knowledge of angular
, the vue-router
is synonymous with the angular router
or if you have any knowledge of react
, it is also synonymous with the react-router
.
The main reason for which we use vue-router
is because it allows us to switch between pages or routes without our page been refreshed or 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 represents 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 URLs from having the #
sign in them, which has also proven not to be good for SEO purposes when URLs 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:
router-view
tag that was placed inside the template, for rendering views.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.
Now let’s 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.
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.
Voilà! This is how to create a simple single-page application.
However, you can make it more complex by:
In the next part of this tutorial, we will pass parameters and use route guards to guard your Application.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!