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

Note the use of the router link in the content. The last thing we need to do to get our app


started is to add the element inside our app. Head to the view, and


include it in the app space:


<div id="app">
<router-view></router-view>
</div>

Load up the app in your browser, not forgetting to start the HTTP server if required. You


should be, at first, presented with your PageNotFound component contents. Navigating to


the following product URL should result in a JavaScript error instead of the 404 page. This


shows the route is correctly picking up the URL but the error is because our ProductPage


component does not contain a template:


#/product/15mm-combo-wrench

If you are presented with the PageNotFound component, check your route's code, as it


means the ProductPage route is not being picked up.


Selecting the right product


With our initial routes set up, we can now proceed with loading the desired product and
displaying the information from the store. Open views/Product.js and create a template


key. To begin with, create a simple

container that displays the title of the product:


const ProductPage = {
name: 'ProductPage',
template: `<div>{{ product.title }}</div>`
};

Viewing this in the browser will instantly throw a JavaScript error as Vue is expecting


the product variable to be an object – but it is currently undefined as we have yet to


declare it. Although the fix for this seems fairly simple at the moment, we need to consider


the case where the product is not yet defined.


Our shop app loads the data CSV asynchronously. This means that the execution of the rest


of the app does not stop while the products are being loaded. Overall, this increases the


speed of our app at the moment we have the products, we can start manipulating and
displaying the list, without waiting for the rest of the app to start.

Free download pdf