Getting the text of the selected item

When binding a <select> element using vue.js v-model , how do you get the selected option text as opposed to the selected parameter value?

In HTML:

 <select v-model="selected" options="myOptions"></select> 

In JS:

 myOptions: [{ text: 'Blue', value: '1' }, { text: 'Green', value: '2' }] 

What I would like to get is the text β€œBlue” as well as the value β€œ1”, doing something like {{ selected.text }} or {{ selected.value }} . However, you can only do {{ selected }} , which by default returns the selected value.

Link: Vue.js guide for dynamic selection options

+5
source share
2 answers

You can simply use a filter, for example:

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/

+2
source

Actually, you can try combining jquery or just your own js code

Solution with jQuery

HTML:

 <div id='example'> <select v-model="selected" options="myOptions"></select> </div> 

JS:

 var vm = new Vue({ el: '#example', data: { ... }, computed: { selectedtext: { cache: false, //get selectedtext by jquery get: function(){ return $(this.$el).find(":selected").text();} } }, }); 

Solution without jquery

HTML:

 <div id='example'> <select ref="ddl" v-model="selected" options="myOptions"></select> </div> 

JS:

 var vm = new Vue({ el: '#example', data: { ... }, computed: { selectedtext: { cache: false, //get selectedtext directly get: function(){ var ddl = this.$refs.ddl; return ddl.options[ddl.selectedIndex].text; } } }, }); 

In addition, you can create a component to reuse logic and achieve the goal of accessing the selected value using {{selected.text}} or {{selected.value}}.

+1
source

All Articles