Vue Final Project - Part 1 - Setting Up

Create a new project in your doc root directory by running this command (from your doc root dir):

npx vue create vue-final-project

You'll be prompted to configure the project, follow these steps:

  1. Use the down arrow key to choose Manually select features, then press the Enter key
  2. Use the up/down arrows and the space bar (to check or uncheck the features that you want to install), select the following features (uncheck other features that may be checked by derault):
    • Babel
    • Router
  3. Choose 3.x for the version of Vue that you want to use
  4. Enter Y to use History mode for the router
  5. When asked Where do you prefer placing config for Babel, ESLint, etc. Choose In dedicated config files
  6. Enter N when asked to Save this as a preset for future projects It may take a few minutes to download and set up the files for the project.

Note that because we chose to include the router, the files for it are already created:

To run the Vue app enter this command (make sure to cd into the project folder first):

npm run serve

Install Bootstrap:

cd into the project folder (vue-final-project) and run the following command to install bootstrap (and it's dependencies):

npm install bootstrap --save
npm install @popperjs/core --save
npm i bootstrap-icons --save

Note that bootstrap uses the popper javascript library.

Add these imports to main.js (put them just after all the other imports in the file):

import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import "bootstrap-icons/font/bootstrap-icons.css";

To test out Bootstrap, replace the entire contents of the HelloWorld.vue file (in the components folder) with this:

<template>
  <div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
      Launch demo modal
    </button>

    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <i class="bi bi-bootstrap" style="font-size: 1.4rem;"></i>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

Now run the app (make sure you running the command from inside the vue-final-project folder):

npm run serve

When the app loads in the browser you should see a Bootstrapped button that says Launch demo modal. Click this button and you should see a Bootstrap modal window appear that includes a Bootstrap icon. If you are seeing all of these, then it appears that we have installed and configured the Bootstrap components.

Setting Up the JSON Server

Before we start working on the Vue project, we'll use JSON Server to give us a test back-end to work with. Add a file named db.json to the vue-final-project folder, then put this code into the file:

{
    "users":[
        {"id": 7, "firstName":"Bob", "lastName":"Smith", "email":"bob@smith.com", "password":"test", "roleId":1, "active": true},
        {"id": 96, "firstName":"Betty", "lastName":"Smith", "email":"betty@smith.com", "password":"test", "roleId":2, "active": true},
        {"id": 33, "firstName":"Barney", "lastName":"Smith", "email":"barney@smith.com", "password":"test", "roleId":1, "active": false}
    ],
    "roles":[
        {"id": 1, "name": "Standard User", "description": "A standard user"},
        {"id": 2, "name": "Admin", "description": "A user with elevated permissions"}
    ]
}

To start the JSON server, cd into the vue-final-project folder and run this command (if you are using VS Code you can create another terminal by clicking the + sign):

npx json-server --watch db.json --port 8888

Verify that the JSON server is running by opening this url in your browser: http://localhost:8888/users

Note that anyone who knows the url to our JSON server CAN simply make a request to fetch all users and would then see all the user passwords. The JSON server is not secure and should never be used in production. But it makes it very easy for us to simulate a backend web service so that we can prototype the front end.

To make it easy to launch the JSON server you can add this to the scripts object inside the package.json file:

"json": "json-server --watch db.json --port 8888"

Now you can start the server by running this command (make sure the terminal is in the project folder):

npm run json

Install Axios

We'll use the Axios library to make ajax calls to the JSON server. To install Axios, run this command:

npm install axios --save

Set Up the Git Repository

At this time you should initialize a git repository in the vue-final-project folder and push it to GitHub or Bitbucket.

Adding Your Own Style Sheet

Create a file in the assets folder named main.css and put this code in it (it's just for testing):

body{ background-color: green;}

In order to incorporate the style sheet into the Vue app, you must 'import' it in main.js by adding this line (you can put it under the othe import statements):

import "./assets/main.css"

Run the app, and you should see a green background. You can go ahead and comment out the code in main.css to get rid of the green.

Create a Data Access Component with Axios

In the src folder, create a file named api.js and put this code in it:

import axios from 'axios'

let apiURL = 'http://localhost:8888'    // FOR REQUESTS TO THE JSON SERVER

const ax = axios.create({
    baseURL: apiURL
});
console.log("REQUESTS ARE BEING SENT TO: " + apiURL);

export function getAllUsers(){
    return ax.get("users/").then(resp => (resp.data)).catch(error => errorHandler("Error Getting All Users:" + error));
}

export function getAllRoles() {
    return ax.get("roles/").then(resp => (resp.data)).catch((error) => errorHandler("Error Getting All Roles:" + error));
}

function errorHandler(msg){
    console.log("API ERROR", msg);
    throw new Error(msg); // because we throw an error here, we can catch it in our components.
}

A few things to note about this module:

  1. It imports the Axios library, creates an instance, and configures the base url to point to our JSON server. We will have to modify the apiURL variable when we start sending the requests to the API project that we'll work on in the Adv Topics class.
  2. It exports a function called getAllUsers(), which returns a promise that can be used to extract the users. Note that when the Axios get() method completes it recieves a response object, which includes the users as it's data property. The then() simply returns resp.data. You'll see how we make use of the getAllUsers() method in just a moment.
  3. It exports a function called getAllRoles() which works much like getAllUsers().
  4. It creates a (private) function that we can use as our error handler. For now, it simply console loggin the error, but we could add code to handle errors in other ways. The nice thing about this is that all of our API errors will go through this function.

Your project should now have all of the dependent packages installed, we can start to build the UI components.