When binding a <select> element using vue.js's v-model, how would you get the selected option text as opposed to the selected option value?
In HTML:
<select v-model="selected" options="myOptions"></select>
In JS:
myOptions: [{ text: 'Blue', value: '1' }, { text: 'Green', value: '2' }]
What I would want to retrieve is both the text 'Blue' as well as the value '1' by doing something like {{ selected.text }} or {{ selected.value }}. However, you can only do {{ selected }} which returns the selected value by default.
Ref: Vue.js guide for Dynamic Select Options
You can just use a filter, like this:
html:
<div id='vm'>
    Formatted value:<b> {{city | cityFormatter}} </b><br/>
    <br/>
    <select v-model="city" options="cities"></select>
</div>
js:
var vm = new Vue({
  el: '#vm',
  data: {
      city: 'city1',
      cities: [{text: 'Toronto', value: 'city1'}, 
               {text: 'Orleans', value: 'city2'}]
  },
  filters: {
      cityFormatter: function(val) {
          var newVal = '';
          this.cities.map(function(el){ 
              if (val == el.value){
                  newVal = el.value + ' ' + el.text;
              }
          });
          return newVal;
      }
  }
});
Working example: http://jsfiddle.net/qfy6s9Lj/9/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With