Search code examples
javascripthtmlvuejs2html-selectv-model

Vue V-Model Initiation Losses Selects Selection


I'm having an issue initializing Vue on certain types of html elements, take a look at the following code:

new Vue({
  el: '#app',
  data: {
    test: ''
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  Without Vue:
  <!-- Non-Vue select defaults to selected value -->
  <select>
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
  </select>

  <br /> 
  <br /> 
  
  With Vue:
  <!-- Vue enabled list loses selection -->
  <select v-model="test">
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
  </select>
</div>

When I start Vue, it seems any "selects" you declare the v-Modal on lose their selected value. This is as described in the documentation:

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.

Now I can do this, but for each select I now need to write a bit of JS outside of Vue to populate/repopulate the selects default value(by populating the "data" property, or reselecting the previously selected value post Vue deceleration).

Is there an easier way of doing this? Maybe some sort of option or tag I can feed to Vue to "persist" values inherited from the initial state of the HTML control?


Solution

  • @b0nyb0y answer is technically correct, but since it doesn't solve my specific issue I'd figure I'd include my hacky workaround here for future reference(only works for selects):

    var itemsToRestore = [];
    $('select[v-model]').each(function (index, value) {
        itemsToRestore.push({
            vModelProperty: $(value).attr("v-model"),
            selectedValue: $(value).val()
        });
    });
    
    var thisVue = new Vue({
        //Put your vue code here
    });
    
    itemsToRestore.forEach(function (value) {
        thisVue[value.vModelProperty] = value.selectedValue;
    });