Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Using Vue-Router Dynamic Routes to Load Data Chapter 9

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 going to be loading a CSV file and, using two plugins, converting it
into a useable JSON object. The three options you have are:



  1. Storing the file locally

  2. Using a remote server or

  3. Using a local server


Let's run through each option, with the advantages and disadvantages for each.


Storing the file locally


The first option is to convert the CSV to JSON appropriately once, and then save the output
in a file. You'll need to assign it to a variable in the file and load the JSON before your


libraries. An example might be creating a data.json and updating it to be assigned to a


variable:


const products = {...}

You can then load the JSON file in your HTML:


<script type="text/javascript" src="data.json"></script>
Free download pdf