-1

在我的 Vue 组件中,我有两个来自数据库的名为 categories 和 product 的数组。类别数组是一个对象数组,比如它有 id、type、name、value,而 products 数组也有 id、type、name、parent_id、value。products 中的 parent_id 是类别的 id。我想根据选择选项中的类别显示产品。例如,如果类别类型 A,则产品将为 B、C、D,或者如果类别类型 B,则产品将为 X、Y、Z。我该怎么做?

4

1 回答 1

0

第 1 步:使用选项创建html模板select

 <template>
  <div id="app">
    <div class="row">
      <label>Category </label>
      <select @change="onChangeCategory" v-model="selectedCategory">
        <option value="">Select Category</option>
        <option
          v-for="(category, index) in categories"
          :key="index"
          :value="category">
          {{ category.name }}
        </option>
      </select>
    </div>
    <div class="row">
      <label>Product </label>
      <select v-model="selectedProduct">
        <option value="">Select Product</option>
        <option
          v-for="(product, index) in filteredProducts"
          :key="index"
          :value="product">
          {{ product.name }}
        </option>
      </select>
    </div>
    <p v-if="selectedCategory">Selected Category {{ selectedCategory }}</p>
    <p v-if="selectedProduct">Selected Product {{ selectedProduct }}</p>
  </div>
</template>

第 2 步:创建模型data

data() {
  return {
    selectedCategory: "",
    selectedProduct: "",
    filteredProducts: [],
    categories: [
      {
        id: 1,
        type: "Food",
        name: "Food",
        value: "Food",
      },
      {
        id: 2,
        type: "Drinks",
        name: "Drinks",
        value: "Drinks",
      },
    ],
    products: [
      {
        id: 1,
        type: "Food",
        name: "Chiken 65",
        parent_id: 1,
        value: "001",
      },
      {
        id: 2,
        type: "Food",
        name: "Magie",
        parent_id: 1,
        value: "002",
      },
      {
        id: 3,
        type: "Food",
        name: "Mutton Roast",
        parent_id: 1,
        value: "003",
      },
      {
        id: 4,
        type: "Drinks",
        name: "Pepsi",
        parent_id: 2,
        value: "004",
      },
      {
        id: 5,
        type: "Drinks",
        name: "Beer",
        parent_id: 2,
        value: "005",
      },
      {
        id: 6,
        type: "Drinks",
        name: "7Up",
        parent_id: 2,
        value: "006",
      },
    ],
  };
},

第 3 步:onChange为类别添加

methods: {
  onChangeCategory() {
    this.selectedProduct = "";
    this.filteredProducts = this.products.filter((item) => {
      return item.parent_id === this.selectedCategory.id;
    });
  },
},

演示

于 2021-10-27T10:59:17.527 回答