Categories
Vue Answers

How to Get the Text of the Selected Option Using Vue.js?

Spread the love

Sometimes, we want to get the text of the selected option using Vue.js.

In this article, we’ll look at how to get the text of the selected option using Vue.js.

Get the Text of the Selected Option Using Vue.js

To get the text of the selected option using Vue.js, we can get the selected value by setting the value prop of the option element to an object.

Then we can bind the selected value prop to a reactive property with v-model .

For instance, we can write:

<template>
  <div id="app">
    <select v-model="selected">
      <option :value="p" v-for="p of products" :key="p.id">
        {{ p.name }}
      </option>
    </select>
    <p>{{ selected.name }}</p>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      selected: {},
      products: [
        { id: 1, name: "apple" },
        { id: 2, name: "orange" },
        { id: 3, name: "grape" },
      ],
    };
  },
};
</script>

We pass in p as the value of the value prop.

And we bind the selected option’s value prop value to the selected reactive property with v-model .

Then when we select an option from the dropdown, we can get its name property value to get the text of the selected option.

Conclusion

To get the text of the selected option using Vue.js, we can get the selected value by setting the value prop of the option element to an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *