APJ APJ - 1 month ago 17
jQuery Question

How to dynamically create a new div using v-for in Vue.js?

I want to create div's dynamically based on the number of elements present in an array. The div's contain the html element created by ProgressBar.js.

This the Vue.js code



import ProgressBar from 'progressbar.js'
var bar;

export default {
data() {
return {
fitness: ['Dietary Intake', 'Exercise'],
val: 0.65
}
},

mounted(){
this.showProgressBar(this.val);
},


created: function() {

},

methods:{
showProgressBar: function(val){
new ProgressBar.Circle('#container',{
trailColor: 'gainsboro',
trailWidth: 20,
color: 'teal',
strokeWidth: 20
}).animate(val);
}
}
}

<div class="content" v-for="fitness in fitness">
<span>{{ fitness }}</span>
<div id="container"></div>
</div>




I am trying to get done something like this,

enter image description here

Since an id is associated with only one div, I am not able to execute a new ProgressBar.Circle object that would create another div. Is there a way to dynamically create a new div with different a id inside the v-for every time the new ProgressBar.circle is executed? Can somenone please help me out here?

Answer Source

One solution could be give unique ids to each container div and create progress bars for each of them.

Try the code below -

import ProgressBar from 'progressbar.js'
var bar;

export default {
  data() {
    return {
      fitness: ['Dietary Intake', 'Exercise'],
      val: [0.65, 9]
    }
  },

  mounted() {
    this.showProgressBar();
  },


  created: function() {

  },

  methods: {
    showProgressBar: function() {
      this.fitness.forEach((f, i) => {
        new ProgressBar.Circle('#container-' + i, {
          trailColor: 'gainsboro',
          trailWidth: 20,
          color: 'teal',
          strokeWidth: 20
        }).animate(this.val[i]);
      });

    }
  }
}
<div class="content" v-for="(f, index) in fitness">
  <span>{{ f }}</span>
  <div v-bind:id="`container-${index}`"></div>
</div>

Update - val can be an array. And its values can be referenced from the within the showProgressBar function.

I am assuming the length of fitness and val arrays are the same.