sopatd
sopatd

Reputation: 27

How to Dynamically Add Elements in Vue.JS?

I am having a little trouble figuring out how to dynamically add elements in Vue. I tried using the V-for as a for loop, however, the output is just the second item in the array. My goal is to create a new box for each of the array items.

The first block is my script code containing my two arrays. The second block is the template or HTML. I tried to loop through each of the numbs array and create a new box in each instance, however, I am having trouble creating new boxes for each element in the array.

<script>
export default{
  data(){
    return{
      numbs: ['Application 1', 'Application 2'],
      applications: [
        { ver: '0.99911', status: 'Ready for Sale', deploymentD: '09/10/2020', deploymentC: 'XXXX'},
        { ver: '0.99911', status: 'Ready for Sale', deploymentD: '09/10/2020', deploymentC: 'XXXX'}

      ]
    }
  }
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div class="body">

  <div class="box"
  v-for="(demo, index) in numbs"
  :key="index">
    <div class="heading">
      {{demo}}
    </div>
    <button class="info"><router-link to = "/viewapp">View</router-link></button>
    <button class="edit"><router-link to = "/editapp">Edit</router-link></button>
    <img class ="place" src="../images/imageinsert.jpg" />
    <div class ="summary" 
      v-for="(apps, index) of applications"
      :key="index">
      Application Version {{apps.ver}}
      {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}
    </div>
    </div>

   
</div>
</template>

Here is an image of how the code currently runs. It prints out the last element of both arrays

Any help is greatly appreciated!!

Upvotes: 0

Views: 474

Answers (1)

JakeParis
JakeParis

Reputation: 11210

To loop through an array and create an element for each item, you use the v-for directive. You use it like so:

<div class="summary" v-for="(apps, index) in applications" :key="index">
   Application Version {{apps.ver}}
   {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}
</div>

You have v-for=(apps, index) for applications" (it should be in not for)

Also, you are using the index variable in both the inner and outer for loops. That's bound to cause an issue.

Upvotes: 1

Related Questions