Vue get text of selected option: In Vue, when a select element’s value changes, a change event is triggered. This event object contains a target property which refers to the select element itself. From there, we can access the options property which gives us a list of all available options within the select element. By looping through this list, we can check each option’s selected property to determine which one was selected. Once we’ve identified the selected option, we can access its text property to retrieve the text content of that option. By combining these steps, we can easily retrieve the selected option’s text in Vue.
How can I use Vue get text of selected option in a dropdown list?
To get the text of the selected option in a dropdown list in Vue, you can use the v-model
directive to bind the selected option value to a data property.
Then, you can use a watch
function to monitor changes to the selected option value and update a separate data property with the corresponding option text.
You can then display the selected option text using an v-if
directive with the selectedOptionText property.
Vue get text of selected option Example
<div id="app">
<select id="my-select" v-model="selectedOption">
<option disabled value="">Please select one</option>
<option v-for="option in options" :key="option.value" :value="option.value">{{ option.text }}</option>
</select>
<p v-if="selectedOptionText">The selected option is: {{ selectedOptionText }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
selectedOption: '',
options: [
{ value: '1', text: 'Option 1' },
{ value: '2', text: 'Option 2' },
{ value: '3', text: 'Option 3' },
],
selectedOptionText: '',
};
},
watch: {
selectedOption(newVal) {
// Find the selected option based on its value
const selectedOption = this.options.find(
option => option.value === newVal
);
// Update the selected option's text
this.selectedOptionText = selectedOption ? selectedOption.text : '';
},
},
});
</script>