2

I have a dropdown that gets populated from an array in my Vue model, like so:

<!-- First dropdown -->
<select v-model="building">
  <option v-for="building in buildings" v-bind:value="building.id">
      {{ building.name }}
  </option>
</select>
<!-- Entries Input -->
<input v-model="entries" type="number">

After the user selects this dropdown and clicks a button, a bunch of other dropdowns will be created (the amount depends on the number the user typed in another input field):

<!-- Dynamically created dropdowns -->
<div v-for="entry in entries">
  <select>
    <option v-for="building in buildings" :selected="building.id == building">
      {{ building.name }}
    </option>
  </select>
</div>

I need the dynamically created dropdowns to have the same selection as the first dropdown. I can't bind them via v-model because I need each of them to be able to be changed without affecting the other ones.

Any idea how to do this? I thought my code :selected="building.id == building" would work but it does not seem to.

1
  • 1
    You're using building for a data item and also for a v-for alias. Commented Feb 1, 2019 at 20:00

1 Answer 1

1

Try to bind your second dropdown to a computed property based on the first one as follows :

 computed:{
          cpt_building:{
                    get(){
                      return this.building;
                      },
                    set(value){
                     //use your value whatever you want
                      }
                }

template :

  <div v-for="entry in entries">
     <select v-model="cpt_building">
       <option v-for="build in buildings" :selected="build.id == building">
         {{ building.name }}
       </option>
     </select>
   </div>

or you could create another data property and changing it by watching the first one.

   data(){
        return{
           building:0,
           building2:0,
           ...
            }
          },
    watch:{
         building(val){
              this.building2=val;
               }
           }

template :

  <div v-for="entry in entries">
     <select v-model="building2">
       <option v-for="build in buildings" :selected="build.id == building">
         {{ building.name }}
       </option>
     </select>
   </div>
Sign up to request clarification or add additional context in comments.

3 Comments

This is a helpful start. However, wouldn't all of the dropdowns then be bound to cpt_building, so if one of them changed then they all would?
the second select depends on the first one and the first one doesn't
This is the correct answer, I'm just trying to understand why it works. I'll read up on computed properties now then. Thanks.

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.