我试图在一条路线下显示多个类别,单击第一个类别显示我的产品,但是当我单击另一个类别时,它不会显示产品,直到硬刷新我的页面,该页面现在显示该类别下的产品列表._id 这是我进入类别路线的方式
<nav class="navbar-end">
<div
class="pt-4 p-3"
v-for="category in categories"
:key="category._id"
>
<router-link :to="`/categories/${category._id}`">
{{ category.type }}
</router-link>
</div>
</nav>
Run Code Online (Sandbox Code Playgroud)
这是我的脚本标签,用于获取类别下的产品列表。_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>
Run Code Online (Sandbox Code Playgroud)
这是我的类别路线
{
path: "/categories/:id",
name: "Category",
component: Category
},
Run Code Online (Sandbox Code Playgroud)
我在单击第一个类别后获得了产品,但单击另一个类别会更改我的category.id url,但直到我硬刷新后才会更新,现在显示产品列表,请问如何在同一category.id上显示产品硬刷新路线
那是因为块中的代码mounted仅执行一次要每次选择不同类别时进行获取,您可以定义一个方法来执行 api 调用并在内部触发watch它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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
637 次 |
| 最近记录: |