Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set initial model value if model is an array

How do I set the default value of a model if it is part of an array?

new Vue({
  data() {
    return {
      value: 1,
      values: [],
      products: [{
        name: 'test 1',
      },
      {
        name: 'test 2',
      }]
    }
  },
  created() {
    for (i = 0; i < products.length; i++) {
      this.values.push(1);
    }
  }
}).$mount('#app')
@import url(https://unpkg.com/vue-range-component@1.0.2/dist/vue-range-slider.min.css);

* {
  margin:0;
  padding:0;
  box-sizing:border-box;
}

.app-content {
  padding:40px 15px;
}
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/vue-range-component@1.0.2/dist/vue-range-slider.min.js"></script>
<div id="app">
  <div class="app-content">
    <div v-for="(product, index) in products">
      <p>
        {{ product.name }}: {{ values[index] }}
      </p>
      <vue-range-slider v-model="values[index]" min="0" max="10"></vue-range-slider>
    </div>
  </div>
  <div>example of working if not an array:</div>
  <p>
    this works: {{ value }}
  </p>
  <vue-range-slider v-model="value" min="0" max="10"></vue-range-slider>
</div>

As you can see from the above example, the array sliders don’t show the number after the colon until after you start sliding, where as if you set the default value in the data (as in the single value) then it works fine

So my question is how do you bind a default value to the model when it is an array of unknown size (the products are loaded from an api so there won’t always be 2)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try

for (i = 0; i < this.products.length; i++) {
    this.values.push(1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading