Using Vue-Router Dynamic Routes to Load Data Chapter 9
Using the router params object, load the desired product from the store and assign it to the
product variable to be returned:
const ProductPage = {
name: 'ProductPage',
template: `<div v-if="product">{{ product.title }}</div>`,
computed: {
product() {
let product;
product = this.$store.state.products[this.$route.params.slug];
return product;
}
}
};
The reason we don't assign the value of product straightaway is so we can add some
conditional statements. To ensure we are only loading the product if the store has the data
available, we can add an if() statement to make sure the product's object has keys
available; in other words, has the data loaded?
Add an if statement checking the length of the store product keys. If they exist, assign the
data from the store to the product variable to be returned:
const ProductPage = {
name: 'ProductPage',
template: `<div v-if="product">{{ product.title }}</div>`,
computed: {
product() {
let product;
if(Object.keys(this.$store.state.products).length) {
product = this.$store.state.products[this.$route.params.slug];
}
return product;
}
}
};