Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preselect current value in a select created with v-repeat in Vue.js?

Tags:

vue.js

I create a drop-down menu with v-repeat in Vue.js, and I have a current value where I need to add the selected property to the select tag. It seems that v-if can only be used to control tags, but not properties.

<select name="flavor">
    <option value=""></option>
    <option v-repeat="proposed_value: proposed_values" value="{{ proposed_value }}">{{ proposed_value }}</option>
</select>

I would need something like this:

<option v-repeat="proposed_value: proposed_values" 
    value="{{ proposed_value }}"
    {{ proposed_value == current_value ? 'selected' }}
>
    {{ proposed_value }}
</option>

This is the object used to create the drop-down:

{
   "name": "flavors",
   "current_value": "strawberry",
   "proposed_values": [
     "vanilla",
     "strawberry",
     "lemon"
  ]
}

Is there a way to do this that does not force me to monkey with the object like this?

{
   "name": "flavors",
   "proposed_values": [
     {"name": "vanilla", "selected": ""}
     {"name": "strawberry", "selected": "selected"}
     {"name": "lemon", "selected": ""}
  ]
}

I am using Vue 0.11.10.

like image 535
Watchduck Avatar asked Nov 21 '15 22:11

Watchduck


2 Answers

In Vue 1.0 and later you can just do this

<div id="app">
    <select v-model="selected">
        <option value="val1">Text1</option>
        <option value="val2">Text2</option>
        <option value="val3">Text3</option>
        <option value="val4">Text4</option>
        <option value="val5">Text5</option>
    </select>
</div>

and

new Vue({
    el: '#app',
    data: {
     selected: 'val3'
    }
});

So what will be the selected value in data it will be auto selected in dropdown as we set the model. I don't know if it works in older version as I have started from 1.0

note: Vue.js is awesome :)

like image 83
Nasir Ahmed Avatar answered Oct 18 '22 20:10

Nasir Ahmed


Ran into this issue myself. Solved it with this.

<select v-model="select">
  <template v-for="option in options">
    <option v-bind:value="option" v-bind:selected="option == savedOption">{{ option }}</option>
  </template>
</select>
like image 41
David Brown Avatar answered Oct 18 '22 19:10

David Brown