Home > Enterprise >  Set initial model value if model is an array
Set initial model value if model is an array

Time:01-13

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/[email protected]/dist/vue-range-slider.min.css);

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

.app-content {
  padding:40px 15px;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-range-slider.min.js"></script>
<div id="app">
  <div >
    <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)?

CodePudding user response:

Try

for (i = 0; i < this.products.length; i  ) {
    this.values.push(1);
}
  •  Tags:  
  • Related