Igor Martins
Igor Martins

Reputation: 2047

Set option as selected

I'm trying to use watch o change a select option as selected using vuejs.

This is my select:

<option v-for="option in options" v-bind:value="option._id" :id="option.iso">
  {{ option.name }}
 </option>

My watch function to change the value when data selectedValuechanges

  watch: {
      selectedValue: function() {
          console.log(document.getElementById(this.selectedValue))
          document.getElementById(this.selectedValue).selected = "selected"
      },
...
}

It gets the correctly element. I also tried using selected = true do not work either.

The selected is not applied on the option...

Upvotes: 0

Views: 82

Answers (2)

Matt Oestreich
Matt Oestreich

Reputation: 8528

Something like this should work.. You want to use v-model on the <select> to grab the currently selected value/item.

You can read more about Vue and <select> in the official documentation, if you would like.


CodePen mirror


new Vue({
  el: "#app",
  data: {
    options: ["Blue", "Green", "Red"],
    selected: '', // selected item lives here
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>


<div id="app">
  <div>
    <select v-model="selected">
      <option disabled value="">Please select one</option>
      <option v-for="(option, index) in options" :key="index">{{ option }}</option>
    </select>
    <div style="margin-top: 70px;">
      <span>Selected: <span :style="{color: selected}">{{ selected }}</span></span>
    </div>
  </div>
</div>

Upvotes: 0

Igor Tulmentyev
Igor Tulmentyev

Reputation: 341

If you want to handle an option value when a select changes, you can declare @change event for the select:

<select v-model="selectedValue" @change="onSelectChange(selectedValue)">
  <option v-for="option in options" :value="option.value">
    {{option.value}}
  </option>
</select>

In the event handler you can process a selected value through this or pass the value directly to the method. I prefer the second one, it allows to keep the logic clearer and work in only the context without thinking about all data variables.

  data() {
    const options= [{
      value: 100,
    },{
      value: 101,
    },{
      value: 102,
    }];
    return {
      options,
      selectedValue: null,
    };
  },

  methods: {
    onSelectChange(value) {
      // here you can handle a new value and set what you want, e.g.:
      const newValue = this.options[0].value; 
      this.selectedValue = newValue;
    },
  }

You can run this https://jsfiddle.net/igtulm/swj1u52x/3/

P.S. and please, do not use document.getElementById() and so on to modify an element state bypassing Vue, it's not a proper way to work with it.

Upvotes: 1

Related Questions