Home > Enterprise >  Button that adds a new row when clicked in Vue 3
Button that adds a new row when clicked in Vue 3

Time:09-12

First I must say that I'm a complete newbie in coding and Vue it's the first framework I'm learning and I'm terrible working with arrays at the moment. In the practice I am doing I am displaying the first five elements of the array in a table (I've filtered them in a new variable to do the v-for).

Now I need to add a button that when clicked will show me a new row of the original array, but I'm a bit stuck on how to do it. As u may see in the code below, contactList is the variable that has all the data, but I have no clue how to link it to the filtered one to show more data when clicked.

<template>
  <h1 >Contacts</h1>
  <button type="button"  @click="addRandom">Add random</button>

<div >
  <table >
    <thead>
        <tr>
            <th >Picture</th>
            <th >Name</th>
            <th >Popularity</th>
            <th >Won an Oscar</th>
            <th >Won an Emmy</th>
        </tr>
    </thead>

    <tbody>
        <tr v-for="(element, index) of contactListed" :key="index">
            <td scope="row">
              <img
              :src="element.pictureUrl"
              :alt="element.name   ` image`"
              
            />
            </td>
            <td> {{ element.name }}</td>
            <td>{{ element.popularity }}</td>
            <td>{{ wonAward(element.wonOscar) }}</td>
            <td>{{ wonAward(element.wonEmmy) }}</td>
        </tr>
    </tbody>
  </table>
</div>
  
</template>

<script>
  import contacts from "./contacts.json";
  
  export default {
    data() {
      return {
        contactList: contacts,
        contactListed: contacts.slice(0, 5),
      };
    },
    methods: {
      wonAward(element) {
        if (element === true || element === true){
          return "winner";
        } else {
          return "";
        }
      },
    },
  };
  </script>

CodePudding user response:

You can use a computed variable that holds the first N elements of the array, and have your button increment the value of N, like this:

<script>
  import contacts from "./contacts.json";
  
  export default {
    data() {
      return {
        contactList: contacts,
        nItems: 5
      };
    },
    
    computed: {
      contactListed() {
        return this.contacts.slice(0, this.nItems)
      }
    },
    
    methods: {
      addRow() {
        this.nItems  ;
      },
    
      wonAward(element) {
        if (element === true || element === true){
          return "winner";
        } else {
          return "";
        }
      },
    },
  };
  </script>


  <template>
     ...

    <button @click="addRow()" />

  </template>

  • Related