Gracie
Gracie

Reputation: 956

Getting item properties from a dropdown in Vue.Js

I am struggling to output one of the object properties (SKU) from an item selected in a dropdown box. I have tried a few variants with no success.

How can I access one of the object properties if I don't display it (use an expression) in the dropdown. In essence, how do I show the SKU of an item outside of the dropdown?

<select v-model="selected">
<option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
</option>
</select>
<span>Selected: {{ selected }}</span>
<p>The SKU of your selected item is {{ selected.sku }}</p>

new Vue({
el: '...',
data: {
    selected: 'A',
    options: [
    { text: 'One', value: 'A', sku:'TT5' },
    { text: 'Two', value: 'B', sku:'BB8' },
    { text: 'Three', value: 'C', sku:'AA9' }
    ]
}
})

Upvotes: 0

Views: 1348

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try to bind the whole object to your option element as follows :

<option v-for="option in options" v-bind:value="option">

by this way you could access its properties like :

  <span>Selected: {{ selected.value }}</span>
  <p>The SKU of your selected item is {{ selected.sku }}</p>

Since you need the value property to be passed to the backend you could use a computed property to get the selected the object based on the selected value :

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    selectedVal: 'A',

    options: [{
        text: 'One',
        value: 'A',
        sku: 'TT5'
      },
      {
        text: 'Two',
        value: 'B',
        sku: 'BB8'
      },
      {
        text: 'Three',
        value: 'C',
        sku: 'AA9'
      }
    ]
  },
  computed: {
    selected() {

      return this.options.find(op => {
        return op.value == this.selectedVal
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <select v-model="selectedVal">
    <option v-for="option in options" v-bind:value="option.value">
      {{ option.text }}
    </option>
  </select>
  <br/>
  <span>Selected: {{ selected }}</span>
  <p>The SKU of your selected item is {{ selected.sku }}</p>

</div>

Upvotes: 3

Related Questions