Reader small image

You're reading from  Vue.js 2.x by Example

Product typeBook
Published inDec 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781788293464
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Mike Street
Mike Street
author image
Mike Street

Mike Street (aka mikestreety) is a frontend developer from Brighton, UK. Specializing in Gulp, SCSS, HTML, and Vue, he has been developing websites professionally since 2010. After making his first Vue app as an experimental side project, he's been hooked ever since. When not developing on the web, Mike likes to explore the Sussex countryside on his bike, start a new side-project without finishing the last, or heading to the cinema.
Read more about Mike Street

Right arrow

Using Vue-Router Dynamic Routes to Load Data

In Chapter 8, Introducing Vue-Router and Loading URL-Based Components, we explored Vue-router and its capabilities and functionality. With that knowledge, we can now progress on to making our shop with Vue. Before we jump into the code and start creating, we should first plan how our shop is going to work, what URLs we need, and what components we need to make. Once we've planned our app we can move on to creating a product page.

In this chapter, we are going to:

  • Outline our components and routes, and create placeholder files
  • Load a product CSV file, process it, and cache in Vuex
  • Create an individual product page with images and product variations

Outline and plan your app

First, let's think about the overall app and the user flow.

We are going to be creating a shop without a payment processing gateway. The shop homepage will display a hand-picked list of products. The user will be able to browse the products using categories and narrow down the selection using filters we've made. They will be able to select a product and view more details about it. The product will have variations (size, color, and such) and may have several product images. The user will be able to add a variation to their basket. From there, they can either continue browsing the products and add more to their basket, or proceed to checkout, where they will be asked for their name and address, and to pay. An order confirmation screen will be shown.

The whole shop app will be created in Vue and will run client-side. This will not cover any server...

Create initial files

With the app outlined in the preceding section, we can create the skeletons for our file structure and components. With this app being a large-scale app, we are going to split our files into individual files for each component. This means our files are much more manageable and our main app JavaScript file does not grow out of control.

Although acceptable for development, deploying an app with this number of files could potentially increase your load times depending on how your server is set up. With the traditional HTTP/1.1, browsers have to request and load each file – which is a hindrance if there are multiple files. However, with HTTP/2, you are able to push several files to the user at the same time – in which case, multiple files can somewhat improve the performance of your app.

Whichever method you choose to use with your deployment, it...

Server setup

With our shop, we are going to be loading in a CSV of products on page load. This will simulate gathering stock and product data from a database or API from a point-of-sale system, something online shops with a physical shop might have to deal with.

In a similar way to our Dropbox app earlier in the book, we will be loading external data and saving it into the Vuex store. The issue we will face, however, is when loading a resource via JavaScript; the browsers demand the protocol for the file being requested is via HTTP, HTTPS, or is a CORS request.

This means that we are unable to load a local file using the fetch() technique we used with the Dropbox API as, when viewing our app in the browser, we are loading local assets over the file:// protocol.

We can resolve this issue in a few different ways – which one you choose depends on your circumstance. We are...

Loading CSV

To simulate gathering data from a shop database or point-of-sale, our app is going to load product data from a CSV. CSV, or Comma Separated Values, is a file format often used for sharing data in a database-style way. Think of how you would lay out a list of products in excel or numbers: that is how a CSV file is formatted.

This next step is going to require downloading and including a couple more JavaScript files. If you chose option 1 in the Server setup section – to have your files stored in a JSON file locally – you can skip this step.

The data we're going to be using is example shop data from Shopify. These CSVs have a wide selection of product types and different data, which will test our Vue skills. Shopify has made their example data available for download from a GitHub repository (https://github.com/shopifypartners/shopify-product-csvs-and...

Displaying a single product

With our data stored, we can now begin making our components and displaying content on the frontend. We're going to start by making a product view – displaying product details, variations, and images. We'll move on to creating the category listing page in Chapter 10, Building an E-Commerce Store – Browsing Products.

The first step in making our product view is to create the route, to allow the component to be displayed via a URL. Referring back to our notes at the beginning of the chapter, the product component is to be loaded on the /product/:slug path.

Create a routes array in your Vue-router, with the path and component specified:

const router = new VueRouter({
routes: [
{
path: '/product/:slug',
component: ProductPage
}

]
});

With the layout of the products object explained, we can start to understand...

Displaying product information

With our product loading, filtering, and error-catching in place, we can proceed with displaying the information we need for our product. Each product could contain one or many images, and one or many variations and any combination in-between – so we need to make sure we cater for each of these scenarios.

To see the data available to us, add a console.log(product) just before the return:

product() {
let product;

if(Object.keys(this.$store.state.products).length) {
product = this.$store.state.products[this.$route.params.slug];
if(!product) {
this.productNotFound = true;
}
}

console.log(product);
return product;
}

Open up the JavaScript console and inspect the object that should now be there. Familiarize yourself with the keys and values available to you. Take note that the images key is an array and the variations an object...

Product variations

With this particular dataset, each of our products contains at least one variation but can contain several. This normally goes hand-in-hand with the number of images but does not always correlate. Variations can be things such as color or size.

On our Product object, we have two keys which are going to help us display the variations. These are variationTypes, which list the names of the variations such as size and color, and variationProducts,which contains all of the variations. Each product within the variationProducts object has a further object of variant, which lists all of the changeable properties. For example, if a jacket came in two colors and each color had three sizes, there would be six variationProducts, each with two variant properties.

Every product will contain at least one variation, although if there is only one variation, we may need to consider...

Updating the product details when switching URLs

While navigating through the different product URLs to check variations, you may have noticed that clicking back and forward doesn't update the product data on the page.

This is because Vue-router realizes the same component is being used between the pages, and so, rather than destroying and creating a new instance, it reuses the component. The downside to this is that the data does not get updated; we need to trigger a function to include the new product data. The upside is that the code is more efficient.

To tell Vue to retrieve the new data, we need to create a watch function; instead of watching a variable, we are going to watch the $route variable. When this gets updated, we can load new data.

Create a new variable in the data instance of slug, and set the default to be the route parameter. Update the product computed...

Summary

This chapter has covered a lot. We loaded and stored a CSV file of products into our Vuex store. From there, we created a product detail page that used a dynamic variable in the URL to load a specific product. We have created a product detail view that allows the user to look through a gallery of images and choose a variation from a drop-down list. If the variation has an associated image, the main image updates.

In Chapter 10, Building an E-Commerce Store – Browsing Products,
we will create a category page, creating filtering and ordering functions – helping the user to find the product they want.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Vue.js 2.x by Example
Published in: Dec 2017Publisher: PacktISBN-13: 9781788293464
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Mike Street

Mike Street (aka mikestreety) is a frontend developer from Brighton, UK. Specializing in Gulp, SCSS, HTML, and Vue, he has been developing websites professionally since 2010. After making his first Vue app as an experimental side project, he's been hooked ever since. When not developing on the web, Mike likes to explore the Sussex countryside on his bike, start a new side-project without finishing the last, or heading to the cinema.
Read more about Mike Street