How to Create Vuejs Website with Vue CLI And Vue Router

Create Vuejs Website with Vue CLI

The first two things that come to my mind when I think about creating a website with Vuejs are Vue CLI and Vue Router, but Why? First, Vue CLI makes

me focus on writing codes for my website so now wasting the time to set up all the tools because it comes with the basic tools you need, ensures the various build tools work smoothly together, and it has a very good structure. Second, Vue Router, the official router for Vue.js, and makes it easy to build a single page application.

What you will learn.

  • Creating a new project with Vue CLI
  • Setting up Vue Router
  • Creating a new page

Creating a new project with Vue CLI

Vue CLI 4.x requires Node.js version 8.9 or above (v10+ recommended). after making sure Node.js is installed on your machine, Let’s install a new Vue CLI package.

# I use npm
npm install -g @vue/cli
# OR
yarn global add @vue/cli

Let’s check if the installation went right by checking the version.

vue --version

Let’s create our new project and name it hello world, via the following command.

vue create hello-world

It will ask you to select a present. I selected the default ([Vue 2] babel, eslint). Go to the project folder:

cd hello-world

let’s start our local server to make sure that everything is okay. and open the like in the terminal http://localhost:8080/ in the web browser.

npm run serve

Looks good!

Setting up Vue Router

For creating routes for our website we are going to use Vue Router but we are going to use Vue CLI for installation as the following command.

vue add router

It will ask if to use history mode for router I chose yes. Let’s start our serve again to check everything.

npm run serve

Now we have links on our home page, Awesome!

Creating a new page

Let’s create a new page for our website, we will name it “contact”. Create a new vue file in ” hello-world\src\views ” folder and name it “Contact.vue”. add the following code.

hello-world\src\views\Contact.vue

<template>
  <div >
    <h1>Contact us</h1>
  </div>
</template>

We need to add the route/ page URL. Open hello-world\src\router\index.js and add the below code to “routes ” after the About.

 {
    path: '/contact',
    name: 'Contact',
    component: () => import( '../views/Contact.vue')
  }

Finally open hello-world\src\App.vue add the link to the “contact” page so we can navigate to the from the home page.

<div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/contact">Contact</router-link>
</div>

Start our server again and click the contact link on the home page.

To compile and minifies for production you need to run the following code, it will create The dist directory and it will be ready to be deployed.

npm run build

I hope I could help you, thanks.

3 thoughts on “How to Create Vuejs Website with Vue CLI And Vue Router

Comments are closed.