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

(singke) #1
Building an E-Commerce Store - Browsing Products Chapter 10

With our category loaded, we can output the title in the template:


template: `<div>
<div v-if="category">
<h1>{{ category.title }}</h1>
</div>
<page-not-found v-if="categoryNotFound"></page-not-found>
</div>`,

We can now proceed with displaying the products on our category page. To do this, we can
use the code from the HomePage component as we have exactly the same scenario – an


array of product handles.


Create a new computed function that takes the current category products and processes


them as we did on the home page:


computed: {
category() {
...
},

products() {
if(this.category) {
let products = this.$store.state.products,
output = [];

for(let featured of this.category.products) {
output.push(products[featured]);
}

return output;
}
}
}

We don't need to check whether the products exist in this function as we are checking


whether the category exists, and that would only return true if the data had been loaded.


Add the component to the HTML and pass in the products variable:


template: `<div>
<div v-if="category">
<h1>{{ category.title }}</h1>
<list-products :products="products"></list-products>
</div>
<page-not-found v-if="categoryNotFound"></page-not-found>
</div>`
Free download pdf