i'm trying to display multiple categories under a route, clicking on the first category display my products ,but when i click on another category it doesn't display the products until hard refresh my page which now displays the lists of products under the categery._id this is how i go to the category route
<nav >
<div
v-for="category in categories"
:key="category._id"
>
<router-link :to="`/categories/${category._id}`">
{{ category.type }}
</router-link>
</div>
</nav>
this is my script tag to get the list of products under a category._id
<script>
import axios from "axios";
export default {
name: "Product",
components: {},
data() {
return {
category: {},
categories: [],
products: [],
catID: []
};
},
mounted() {
axios
.get(
`http://localhost:5000/api/categories/${this.$route.params.id}`,
{}
)
.then(response => {
console.log(response);
this.category = response.data.category;
})
.catch(error => {
console.log(error);
error;
});
axios
.get(`http://localhost:5000/api/products`, {})
.then(response => {
console.log(response);
this.products = response.data.products;
const catID = this.category._id;
// this.products = this.products.filter(
// ({ category }) => catID === category._id
// );
})
.catch(error => {
error;
});
},
computed: {
currentProducts() {
if (!this.category._id) {
return this.products;
}
return this.products.filter(
({ category }) => category._id === this.category._id
);
}
},
methods: {
...mapActions(["addProductToCart"]),
logout() {
localStorage.clear();
this.$router.push("/login");
}
}
};
</script>
this is my category route
{
path: "/categories/:id",
name: "Category",
component: Category
},
i get the products after clicking the first category ,but clicking another category changes my category.id url but doesn't update until i hard refresh ,which now displays the list of product please how can i display the products on the same category.id route with hard refresh
CodePudding user response:
Thats because the code in the mounted
block gets executed only once
To do a fetch everytime when you select a different category, you can define a method that does the api call and trigger it inside watch
and mounted
watch: {
'$route.params.id': {
handler(newVal) {
this.loadCategories(newVal);
}
}
},
mounted() {
this.loadCategories(this.$route.params.id);
axios
.get(`http://localhost:5000/api/products`, {})
.then(response => {
console.log(response);
this.products = response.data.products;
const catID = this.category._id;
})
.catch(error => {
error;
});
},
methods: {
loadCategories(id) {
axios
.get(
`http://localhost:5000/api/categories/${id}`,
{}
)
.then(response => {
console.log(response);
this.category = response.data.category;
})
.catch(error => {
console.log(error);
error;
});
}
}