如何在 select 选项中基于 vue js 中的数组唯一 id 显示数据

How to show data in select option based on array unique id in vue js

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

步骤 1: 使用 select 选项创建一个 html 模板

 <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;
    });
  },
},

DEMO