[Vuejs]-How to show data in select option based on array unique id in vue js

0👍

Step 1: Create an html template with select option

 <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>

Step 2: Create an model 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",
      },
    ],
  };
},

Step 3: Add an onChange event for category

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

DEMO

Leave a comment