Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filtering them into a new variable for use in a v-for loop.

Now, the challenge is to include a button that when clicked, will reveal a new row from the original array. However, I'm feeling a little lost on how to accomplish this task. As you can see in the code snippet below, contactList holds all the data, but linking it to the filtered data to display more information upon clicking baffles me.

<template>
  <h1 class="display-1 text-primary">Contacts</h1>
  <button type="button" class="btn btn-outline-primary btn-lg" @click="addRandom">Add random</button>

<div class="container container__pos">
  <table class="table table-hover">
    <thead>
        <tr>
            <th class="col col__style">Picture</th>
            <th class="col col__style">Name</th>
            <th class="col col__style">Popularity</th>
            <th class="col col__style">Won an Oscar</th>
            <th class="col col__style">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`"
              class="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>

Answer №1

To display only the first N elements of an array, you can create a computed variable and update its value with a button click event. Here's an example:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

JavaScript and HTML with Node.js

Exploring the world of HTML, running smoothly with a static IP address 192.168.56.152 using apache on the host computer. <!DOCTYPE html> <html > <head> <title>OnlinePage</title> <meta charset="utf-8"& ...

Issue with casl: can() method returns null upon page refresh using F5 command

I've been working on implementing the CASL permissions system into my VueJS 2 project. Everything seems to be working fine, but I have encountered an issue when intentionally refreshing the page (like pressing F5). After the refresh, all can() functio ...

Tips for accessing $parent of ng-repeat from ng-include

In my code, I have a nested ng-repeat structure with an ng-include inside the inner ng-repeat. I am trying to access the outer ng-repeat using $parent within the ng-include. Here is an example of what I am working on: index.html <div ng-repeat="popula ...

Talking about passed properties in Vue.js components

I recently embarked on creating a prototype for a board game using Vue.js. I have some knowledge of JavaScript and was progressing smoothly until I encountered an issue with accessing a property passed with 'props' in a component. Below is the c ...

Tips for adjusting the size of an imported item in Three.js?

Currently, I am utilizing Three.js for my project and I am importing .OBJ file using OBJ LOADER () Everything has been working smoothly thus far, but I have come across an issue that has me stumped. I am trying to figure out how to change the width and he ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

Scene three js appears to be stuck in a perpetual state of emptiness, making it challenging to start

I've encountered a major issue with understanding how to use three.js. Despite my best efforts over the past few days, I haven't been able to successfully implement three.js into my projects. Initially, I attempted using Parcel by starting a new ...

Error in Vue 3 Script Setup with Typescript: Implicit 'any' type for parameter 'el' in Template ref

Could someone help explain why I am receiving an error from TypeScript that says the following? error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)". I am confident that the correct type is set ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

tips for uploading image data using JavaScript

My HTML form sends POST data to my PHP script and uses AJAX for a live preview The issue arises with the image input field in the form Here's an example of the form structure: <form method="post" action="scripts/test.php" enctype="multipart/form ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

A step-by-step guide on splitting by double quotes in Python

I have a string that I need to convert, for example, from STRING to ['S', 'T', 'R', 'I', 'N', 'G']. I've attempted using the following methods: o.split('') and o.split(). Could you ...

Encountering an issue when passing a response using coverage.js

I am utilizing coverage.js to showcase data. When I pass my variable containing the coverage response into an HTML file, similar to how it's done in Angular to display expressions, I encounter a syntax error: <div class="container" style="margin- ...

Implementing functions on React component classes

Recently, I decided to convert a slideshow from w3s schools into a React component. The process involved changing all the functions into methods on the class and setting the initial state to display the first slide. However, upon clicking the buttons or do ...

Handling Errors in Asynchronous Functions with JavaScriptLet's explore the best practices for

I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about wh ...