[Vuejs]-Display only one attribute of arrayed objects in md-autocomplete :md-options

0👍

You can try this :

<template>
  <div>
    <md-autocomplete
      v-model="selectedFruit"
      :md-options="fruitOptions"
      @md-changed="getFruitOptions"
      @md-opened="getFruitOptions"
      @md-selected="getSelected"
    >
      <label>Select fruit</label>
    </md-autocomplete>

    <md-field>
      <label>Price :</label>
      <md-input v-model="selectedFruitPrice" readonly></md-input>
    </md-field>

    <md-field>
      <label>Available Amount :</label>
      <md-input v-model="selectedFruitAmount" readonly></md-input>
    </md-field>
  </div>
</template>

<script>
export default {
  name: "autocomplete",
  data: () => ({
    selectedFruit: null,
    fruits: [
      { name: "Orange", available: "5", price: "$11.0" },
      { name: "Apple", available: "17", price: "$4.56" },
      { name: "Kiwi", available: "1", price: "$25.30" },
    ],
    fruitOptions: [],
    selectedFruitPrice: "",
    selectedFruitAmount: "",
  }),
  methods: {
    getFruitOptions(searchTerm) {
      console.log("getCustomers", searchTerm);
      this.fruitOptions = new Promise((resolve) => {
        if (!searchTerm) {
          resolve(this.fruits.map((x) => x.name));
        } else {
          const term = searchTerm.toLowerCase();
          this.fruitOptions = this.fruits
            .filter(({ name }) => {
              return name.toLowerCase().includes(term);
            })
            .map((x) => x.name);
          resolve(this.fruitOptions);
        }
      });
    },

    getSelected() {
      const selectedFruitDetails = this.fruits.find(
        (obj) => obj.name === this.selectedFruit
      );
      this.selectedFruitPrice = selectedFruitDetails.price;
      this.selectedFruitAmount = selectedFruitDetails.available;
    },
  },
};
</script>

Working Demo : codesandbox

Leave a comment