0

i have the object like this;

fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]

And code in vuejs like this

<select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>

and what i get from this tag it's like this

enter image description here

and what i want to ask is how can i get the value as the id of each option. like a when i select Mango and the value is 003. if you know how to solve this please help me. thank you.

1

2 Answers 2

1

For Your Solution use this -

<template>
    <select name="itemType" v-model="itemType" @change="onChange()" class="form-control">
         <option value="001">Apple</option>
         <option value="002">Banana</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            itemType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.itemType)
        }
    }
}
</script>

My advice use vuetify (v-select)component with vue for better performance.

<template>
     <v-select
        v-model="select"
        :items="fluit"
        item-text="id"
        item-value="name"
        label="Select"
        @input="doSomething"
        return-object/>
</template>

<script>
  export default {
    data () {
      return {
        select: { id:'005', name:"papaya" },
        items: [
           {id:'001', name:"Apple"},
           {id:'002', name:"Banana"},
           {id:'003', name:"Mango"},
           {id:'004', name:"orange"},
           {id:'005', name:"papaya"},
        ],
      }
method:{
      doSomething(){
       console.log(this.select)
      }
    }

    },
  }
</script>

I Hope it will help!

Sign up to request clarification or add additional context in comments.

Comments

0

add a v-model to your select and that is it:

<select v-model="selectedItem">
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"> 
   {{item.name}}
  </option>
</select>

now selectedItem will contain the value of the fruit, working example : https://codesandbox.io/s/fruit-select-vs709

2 Comments

hi dear, thank you i have got it. you are so helpful
the codesandbox is not using a v-for loop to render the options, they are hardcoded one by one. I tested with a non-hardcoded list of options and it fails, so unfortunately it looks like this answer doesn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.