Build an Online Shop with Vue

Creating Routes

Installation and Setup

Not all your Vue apps will require routing. For that reason, Vue does not come pre-packaged with Vue Router. Rather, when you have a need for the router, you can install differently:

npm install --save vue-router

The Vue Router is available as a Vue plugin, therefore, you should use the use method to make it available to your app. Let's start building our application using the code we generated with the CLI earlier.

// ./src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

Create Your First Route

A quick recap -- we are building a mini online store. Such stores are characterized with at least a home page (product listing), a cart/checkout page and an admin page to manage products.

The characteristics already give us a high-level view of the pages. Which means we need three routes for now:

  • Home
  • Admin
  • Cart

To create each of these routes, we need to make Vue components/templates for them. Remember, components are Vue's building block. Therefore, even routes' views are components.

Let's start with the Home Route:

<!-- ./src/components/Home.vue -->
<template>
  <div>
    <div class="title">
      <h1>{{msg}}</h1>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'home',
    data () {
      return {
        msg: 'Welcome to Your Vue.js App'
      }
    }
  }
</script>

Now we can use the Vue Router to create routes and turn our new Home component into a route view:

// ./src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    }
  ]
});

The Router instance takes an object which serves as configuration for the router. The routes property contains an array of routes, and each route is identified by name, accessed by a path and loads a component.