Reputation: 41
I have a getter where all products are stored there, and when I want to get only one product dynamically depending on this.$route.params.id
it doesn't return any value
this code works correctly when I navigate to a certain product, but when I refresh the page I lose everything
computed: {
...mapGetters(["getAllProducts"]),
product() {
return this.getAllProducts.filter(item => {
return item.id === this.$route.params.id;
});
}
}
But if I supplied filter()
with static value in instead of this.$route.params.id
like below it works
product() {
return this.getAllProducts.filter(item => {
return item.id === 1;
});
}
I really don't know what is the problem, despite of in another component in my project I did some filters on some computed properties and it worked
update: the routes config
{
path: "/product/:id",
name: "product-page",
component: ProductPage,
props: true
}
Upvotes: 1
Views: 1638
Reputation: 4014
Route params are usually parsed as strings. Try converting the route param value to number type and then do the match:
product() {
return this.getAllProducts
.filter(item => item.id === Number(this.$route.params.id));
}
Upvotes: 4
Reputation: 1
According to the official docs :
When
props
is set totrue
, theroute.params
will be set as the component props
so add the id
to your props like then use it instead of this.$route.params.id
:
props:['id'], //refers to this.$route.params.id
...
computed: {
...mapGetters(["getAllProducts"]),
product() {
return this.getAllProducts.filter(item => {
return item.id == this.id;
});
}
}
Upvotes: 1
Reputation: 537
Try giving this.$route.params.id as a computed propertly. Then call it in the filter method.
computed: {
...mapGetters(["getAllProducts"]),
routerId() {
return this.$route.params.id;
},
product() {
return this.getAllProducts.filter(item => {
return item.id === this.routerId;
});
}
}
Upvotes: -1