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

It is worth considering which one suits you best; CSV Parser only adds just over 3 KB of


weight to your app, whereas d3 is around 60 KB. Unless you anticipate adding
visualizations later, it is recommended you go to the smaller library – especially as they


execute the same function. However, we'll run through examples for both libraries.


We want to load our product data when the app loads, so our CSV will be loaded and


parsed by the time our components require the data. Because of this, we will be loading our


data in the created() method of Vue.


Loading a CSV with d3


Both plugins load the data in a very similar way, but the data returned varies somewhat –


however, we'll deal with that once we have loaded our data.


Load the d3 library – if you want to try it out, you can use the hosted version:


<script src="https://d3js.org/d3.v4.min.js"></script>

Using d3, we use a function on the d3 object of csv(), which accepts one parameter – the


path to the CSV file. Add the created() function to your Vue instance and initialize the


CSV loader:


new Vue({
el: '#app',

store,
router,
created() {
d3.csv('./data/csv-files/bicycles.csv', (error, data) => {
console.log(data);
});
}
});

Remember the path to your file is relative to the HTML file which is
including your JavaScript file – in this case, index.html.
Free download pdf