Vue Basics Tutorial

In this tutorial, we will be building a website for a bookstore. This will focus on the front-end part of the application.

Setup

We will be using @vue/cli to develop this website.

Begin by opening a terminal and navigating to the directory where you want to save your code. Then, we will use @vue/cli to create the application. We

# install vue-cli if it isn't already
npm install --global @vue/cli
# create the application
vue create curi-bookstore
# select the default option

# enter the new app directory
cd curi-bookstore
# start the dev server
yarn serve

The dev server will automatically update when we change files, so we can leave that running. We will still be working in the terminal, so you will want to open up a new terminal window/tab and navigate to the application's directory. Once you have done that, there are a few packages that need to be installed.

yarn add @hickory/browser @curi/router @curi/vue

The @hickory/browser package will be used to create an object that interacts with the browser to power navigation (e.g. updates the URI in the address bar when you click a link). @curi/router provides the function to actually create the router. @curi/vue gives us a plugin for Vue and some Vue components that interact with the router.

History and Locations

URIs can be broken into parts to identify a location. With a single-page application, we don't care about the URI's protocol (http, https) or its hostname (www.example.com). The properties we care about are the pathname, hash, and query.

// uri = "https://example.com/one?key=value#id
{
  pathname: "/one",
  query: "key=value",
  hash: "id"
}

The routes define what the application renders for a particular location, but we also need to define how the application navigates. When we create the router, we will pass it a history function that will be used to enable navigation.

Curi uses the Hickory library for its history. There are a few Hickory packages to choose from for different environments. For most websites, the @hickory/browser is the right choice for the front end.

We can import the browser function from @hickory/browser in our index file (src/index.js, which create-react-app created for us).

// src/main.js
import Vue from 'vue';
import { browser } from '@hickory/browser';

import App from './App.vue';

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount('#app');

Defining the Routes

Routes are JavaScript objects that define the valid locations for a router. They have a name and a path.

// this is a route
{ name: "Home", path: "" }

A route's name needs to be unique. We will use route names when we navigate within the application. A route's path describes the location pathname that it should match.

The website will start with four routes.

namepathDescription
Home""Lists books available for purchase
Book"book/:id"Details about an individual book
Checkout"checkout""Buy" the books in the shopping cart
Catch All"(.*)"Display a not found page for all other locations

Inside of the src directory, we will create a routes.js file where we can define the application's routes.

touch src/routes.js

We can create an array of routes using the above names and paths.

@curi/router provides a prepareRoutes function, which is used to setup routes for the router. We will pass the routes array to prepareRoutes and export the result of that function call.

// src/routes.js
import { prepareRoutes } from "@curi/router";

export default prepareRoutes([
  {
    name: "Home",
    path: ""
  },
  {
    name: "Book",
    path: "book/:id"
  },
  {
    name: "Checkout",
    path: "checkout"
  },
  {
    name: "Catch All",
    path: "(.*)"
  }
]);

The Router

With the history object created and the routes defined, we are ready to create the router. Back in the src/index.js file, we should import the createRouter function from @curi/router as well as our routes from src/routes.js. Creating the router is done by calling the createRouter function and passing it the history function and the routes array.

// src/main.js
import Vue from 'vue';
import { createRouter } from "@curi/router";
import { browser } from '@hickory/browser';

import routes from './routes';
import App from './App.vue';

Vue.config.productionTip = false;

const router = createRouter(browser, routes);

new Vue({
  render: h => h(App)
}).$mount('#app')

The router is now ready and we can render the application, but first we should do something really important: make the site more accessible.

Announcing Navigation

In a multi-page application, a screen reader will announce navigation to users. This happens automatically when a new Document is loaded. A single-page application reuses its Document, which is great for removing unnecessary server requests, but also means that the navigation is no longer automatically announced.

Curi has a concept of "side effects". These are functions that are called after a navigation happens and are passed an object with data about the navigation.

The @curi/router package provides a few side effects that are useful for websites. For now, we will focus on the announce side effect. The announce side effect returns a string, which sets the text content of a ARIA Live region. Screen readers will detect the changed text and read it to the users.

Let's go ahead and add the announce side effect to the router. We will have it return a string of the response's pathname.

// src/main.js
import Vue from 'vue';
import { createRouter, announce } from "@curi/router";
import { browser } from '@hickory/browser';

import routes from './routes';
import App from './App.vue';

Vue.config.productionTip = false;

const router = createRouter(browser, routes, {
  sideEffects: [
    announce(({ response }) => {
      return `Navigated to ${response.location.pathname}`;
    })
  ]
});

new Vue({
  render: h => h(App)
}).$mount('#app');

The Vue Plugin

We will add router support to the Vue application using a plugin. This plugin does a couple of things. First, it makes some Curi components available within the application. The only one of these components that we will be using is the curi-link. Second, it makes router related values accessible to the components in the application. The router is available as this.$router and the response and navigation (we will cover these next) are grouped under this.$curi. When the CuriPlugin is installed, the router as passed in the options object.

// src/main.js
import Vue from 'vue'
import { createRouter, announce } from "@curi/router";
import { browser } from '@hickory/browser';
import { CuriPlugin } from '@curi/vue';

import routes from './routes';
import App from './App.vue';

Vue.config.productionTip = false;

const router = createRouter(browser, routes, {
  sideEffects: [
    announce(({ response }) => {
      return `Navigated to ${response.location.pathname}`;
    })
  ]
});
Vue.use(CuriPlugin, { router });

new Vue({
  render: h => h(App)
}).$mount('#app');

Rendering with Vue

We can now render our application. We will re-use the provide App.vue file.

Most of the time, the response is the only property you will need to use to render, but the other two may occasionally be useful.

How do we use the response to render? Any way you want. Based on the sample response above, the name stands out as the best way to identify which route matched. We can make this even easier by adding another property to the response: body.

Earlier it was mentioned that response objects can be modified. This is done by returning an object from a route's respond function. respond receives an object with a whole bunch of properties that we can use to help determine how to modify the response, but for the time being, we don't care about any of those. All we need to know is that if we return an object with a body property, that value will be set on our response object.

{
  name: "Home",
  path: "",
  respond() {
    return {
      body: "Home, sweet home."
    };
    /*
      * response = {
      *   body: "Home, sweet home.",
      *   // ...
      * }
      */
  }
}

If the return object's body property is a Vue component, we can render it using <Component :is>.

We haven't actually defined components for our routes yet, so we should throw together some placeholders.

touch src/components/Home.vue src/components/Book.vue \
  src/components/Checkout.vue src/components/NotFound.vue
<!-- src/components/Home.vue -->
<template>
  <article>
    <p>Home</p>
  </article>
</template>
<!-- src/components/Book.vue -->
<template>
  <article>
    <p>Book</p>
  </article>
</template>
<!-- src/components/Checkout.vue -->
<template>
  <article>
    <p>Checkout</p>
  </article>
</template>
<!-- src/components/NotFound.vue -->
<template>
  <article>
    <p>Not Found</p>
  </article>
</template>

These components can be imported in src/routes.js and attached to their respective routes.

// src/routes.js
import { prepareRoutes } from "@curi/router";

import Home from './components/Home';
import Book from './components/Book';
import Checkout from './components/Checkout';
import NotFound from './components/NotFound';

export default prepareRoutes([
  {
    name: "Home",
    path: "",
    respond() {
      return {
        body: Home
      };
    }
  },
  {
    name: "Book",
    path: "book/:id",
    respond() {
      return {
        body: Book
      };
    }
  },
  {
    name: "Checkout",
    path: "checkout",
    respond() {
      return {
        body: Checkout
      };
    }
  },
  {
    name: "Catch All",
    path: "(.*)",
    respond() {
      return {
        body: NotFound
      };
    }
  }
]);

We can now update App.vue to render response.body as a component, which as mentioned above is available through this.$curi.

<!-- src/App.vue -->
<template>
  <component :is="$curi.response.body" />
</template>

We can also remove the HelloWorld component.

rm src/components/HelloWorld.vue

At this point in time our app is rendering, but is isn't very interesting because we cannot navigate between locations.

The CuriPlugin makes a curi-link component available with the appliaction. We can use that to navigate between locations within our application.

We will start with creating a navigation menu component with links to our home page and checkout page.

touch src/components/NavMenu.vue
<!-- src/components/NavMenu.vue -->
<template>
  <nav>
    <ul>
      <li>
        <curi-link name="Home">Home</curi-link>
      </li>
      <li>
        <curi-link name="Checkout">Checkout</curi-link>
      </li>
    </ul>
  </nav>
</template>

We can import that in our App.vue file and add it to our template. This is a good opportunity to also add some structure to the elements in the template.

<!-- src/App.vue -->
<template>
  <div>
    <header>
      <nav-menu />
    </header>
    <main>
      <component :is="$curi.response.body" />
    </main>
  </div>
</template>

<script type="src/javascript">
  import NavMenu from './components/NavMenu';

  export default {
    name: 'app',
    components: {
      'nav-menu': NavMenu
    }
  };
</script>

We want to be able to link to individual books from the home page. First, we need data about the books. For now, we're going to hard-code the books in the src/books.js module.

touch src/books.js

You can copy+paste or modify the data, but the structure of the provided data should stay the same.

// src/books.js
export default [
  {
    id: 0,
    title: 'The Name of the Wind',
    author: 'Patrick Rothfuss',
    published: '2007',
    pages: 662
  },
  {
    id: 1,
    title: "The Wise Man's Fear",
    author: 'Patrick Rothfuss',
    published: '2011',
    pages: 994
  },
  {
    id: 2,
    title: 'The Way of Kings',
    author: 'Brandon Sanderson',
    published: '2010',
    pages: 1007
  },
  {
    id: 3,
    title: 'A Storm of Swords',
    author: 'George R.R. Martin',
    published: '2003',
    pages: 1177
  },
  {
    id: 78,
    title: 'Words of Radiance',
    author: 'Brandon Sanderson',
    published: '2014',
    pages: 1087
  }
];

The data can be imported in the Home component. We will iterate over the books with a curi-link to each one.

<!-- src/components/Home.vue -->
<template>
  <article>
    <ul>
      <li v-for="b in books" :key="b.id">
        <curi-link name="Book" :params="{ id: b.id }">
          {{b.title}} by {{b.author}}
        </curi-link>
      </li>
    </ul>
  </article>
</template>

<script>
  import books from '../books';

  export default {
    name: 'home',
    data() {
      return { books };
    }
  }
</script>

Now that we can navigate to the books, we should fill out the UI for the Book component. We will once again import the books.js data. We can use params.id to select the correct book. params.id is a string, so we will need to parse it into an integer. Sometimes there won't be a valid book for the params.id. In that case, we will also want to display a message that the requested book could not be found.

<!-- src/components/Book.vue -->
<template>
  <article v-if="book">
    <h1>{{book.title}}</h1>
    <h2>by {{book.author}}</h2>
    <p>Published in {{book.published}}</p>
    <p>{{book.pages}} pages</p>
  </article>
  <article v-else>
    <p>
      The requested book could not be found
    </p>
  </article>
</template>

<script>
  import books from '../books';

  export default {
    name: 'book',
    computed: {
      book() {
        const id = parseInt(this.$curi.response.params.id, 10);
        return books.find(b => b.id === id);
      }
    }
  }
</script>

Let's go shopping

We want to be able to add books to our shopping cart. Since this is a play site, we will store the cart data in memory.

touch src/cart.js

The shopping cart implementation will be a JavaScript Map. We can call its set method to add books, its clear method to reset the cart, and iterate over its entries with a for...of loop.

// src/cart.js
const cart = new Map();

export default {
  add(book, quantity) {
    cart.set(book, quantity);
  },
  items() {
    const books = [];
    for (let [book, quantity] of cart.entries()) {
      books.push({
        title: book.title,
        quantity
      });
    }
    return books;
  },
  reset() {
    cart.clear();
    return [];
  }
};

As stated above, we can access our router in the Book component using this.$router. The router's navigate function can be used to navigate to a new location. This means that when the user clicks a button to add a book to their shopping cart, we can automatically navigate to the checkout page.

We also want to import our shopping cart API so that we can add a book to the cart.

<!-- src/components/Book.vue -->
<template>
  <article v-if="book">
    <h1>{{book.title}}</h1>
    <h2>by {{book.author}}</h2>
    <p>Published in {{book.published}}</p>
    <p>{{book.pages}} pages</p>
    <button type="button" v-on:click="onClick">
      Add to Cart
    </button>
  </article>
  <article v-else>
    <p>
      The requested book could not be found
    </p>
  </article>
</template>

<script>
  import books from '../books';
  import cart from '../cart';

  export default {
    name: 'book',
    computed: {
      book() {
        const id = parseInt(this.$curi.response.params.id, 10);
        return books.find(b => b.id === id);
      }
    },
    methods: {
      onClick: function() {
        cart.add(this.book, 1);
        const url = this.$router.url({ name: "Checkout "});
        this.$router.navigate({ url });
      }
    }
  }
</script>

Finally, we can update our Checkout component to display the books in the shopping cart. To do this, we will import our cart and books. Our cart only stores book ids, so we will need to merge the book data with the cart data.

When a user "buys" the books in their shopping cart, we need to clear out the cart. We will also replace the current location with one whose location.hash is the string "thanks". When that is present in the URI, we can render a "Thanks for your purchase" message to "confirm" the purchase.

<!-- src/components/Checkout.vue -->
<template>
  <article v-if="books.length">
    <h1>Checkout</h1>
    <ScrollableTable>
      <thead>
        <tr>
          <th>Title</th>
          <th>Quantity</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="book in books" :key="book.title">
          <td>{{book.title}}</td>
          <td>{{book.quantity}}</td>
        </tr>
      </tbody>
    </ScrollableTable>
    <button type="button" v-on:click="onClick">
      Buy
    </button>
  </article>
  <article v-else-if="$curi.response.location.hash === 'thanks'">
    <p>Thanks for your purchase!</p>
  </article>
  <article v-else>
    <p>The cart is currently empty</p>
  </article>
</template>

<script>
  import cart from '../cart';

  export default {
    name: 'checkout',
    data() {
      return {
        books: cart.items()
      };
    },
    methods: {
      onClick: function() {
        this.books = cart.reset();
        const url = this.$router.url({
          name: "Checkout",
          hash: "thanks"
        });
        this.$router.navigate({ url, method: "replace" });
      }
    }
  }
</script>

What's next?

We now have a functional website built with Vue and Curi. What should you do next? Build another site! You can also check out the guides for information on advanced techniques.

  1. Setup
  2. History and Locations
  3. Defining the Routes
    1. Path basics
  4. The Router
    1. Announcing Navigation
    2. The Vue Plugin
  5. Rendering with Vue
    1. Responses and Navigation
  6. Navigating between locations
    1. The <curi-link> Component
    2. A Navigation Menu
    3. Linking to Books
  7. Let's go shopping
    1. The Router's URL & Navigate Methods
  8. What's next?