下面是我的vue sfc,它应该显示由给定品牌ID销售的产品列表,但由于某种原因,当我获取产品并通过www.example.com筛选它们时,products数组仍然未定义brand.id the products array is still undefined
<script setup>
import { useRoute } from 'vue-router'
import { ref, computed } from "vue";
import axios from 'axios'
import { useProductsStore } from "../stores/products";
const store = useProductsStore();
const baseURL = "http://127.0.0.1:8000/"
const route = useRoute()
const id = route.params.id
store.fetchProducts()
const getProductsById = store.getProductsByBrandId
</script>
<template>
<div class="brandDetails">
<div>
<h2>Brand Details</h2>
ID: {{ id }}
</div>
<div>
<h2>Products</h2>
<p v-for="product in getProductsById(id)">{{ product.name }}</p>
</div>
</div>
</template>
这是我的pinia商店
import { defineStore } from "pinia";
import axios from "axios";
export const useProductsStore = defineStore("products", {
state: () => {
return {
products: [],
vendors: [],
brands: [],
};
},
getters: {
getProducts: (state) => {
return state.products;
},
getVendors: (state) => {
return state.vendors;
},
getBrands: (state) => {
return state.brands;
},
getProductsByBrandId: (state) => {
return (id) => state.products.filter((x) => x.brand.id === id);
},
},
actions: {
async fetchProducts() {
try {
const data = await axios.get("http://127.0.0.1:8000/products.json");
this.products = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
async fetchVendors() {
try {
const data = await axios.get("http://127.0.0.1:8000/vendors.json");
this.vendors = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
async fetchBrands() {
try {
const data = await axios.get("http://127.0.0.1:8000/brands.json");
this.brands = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
},
});
我不确定我做错了什么,但我认为问题是它试图过滤一个尚未定义的数组。如果是这样,我如何在过滤它之前确定它已定义,或者可能有更好的方法来做这件事,我只是trippin
任何帮助都很感激
1条答案
按热度按时间k2fxgqgv1#
∮所以这就是我如何让它工作
我会把它贴在这里,以防其他人陷入同样的事情,我做了
这可能是一些非常基本的东西,我应该知道,但无论如何,它在这里
品牌详情
非常感谢所有帮助我的人!