How can I pass a data object to a backend function and use it to dynamically create a new table row in VueJS?

I am looking for a way to pass an object through a function and then dynamically add a table row with the data from that object. In my backend, I need to first send the "row" object to the function. While I know how to add table rows using vanilla JS and jQuery, I am unsure of how to accomplish this in VueJS. Can you provide guidance on achieving this?

HTML TABLE

<table id="tableID"></table>

HTML CODE NEEDED TO BE ADDED USING THE DATA FROM THE "ROW" OBJECT

<tr v-for="item in items" :key="item.Id" v-bind:id="item.Id" class="e-tr">
                                <td><input type="text" class="c-cell" v-model="item.Type"/></td>
                                <td><input type="text" class="c-cell" v-model="item.Model"/></td>
                            </tr>

JAVASCRIPT

add: function () {
            var row = { Id: 0, Type: 0, Model: 0 };
            fetch('/Cont/Send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(row)
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function () {
                    /*insert additional HTML code here?*/
                })
        }

Answer №1

If you are storing the data in 'items', you must update its value within the 'add' method and also retain the reference to the component itself using 'this'. One approach, utilizing async/await, could be:

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      items: []
    };
  },
  methods: {
    async sendMyData() {
      const response = await fetch(
        "/Cont/Send", {
            // Configure HTTP method and headers
        }
      );
      const data = await response.json();
      this.items = Object.values(data.bpi);
    }
  }
};
</script>

Another way would be using promise chaining (then):

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      items: []
    };
  },
  methods: {
    sendMyData() {
      const self = this;
      fetch("/Cont/Send", {
            // Configure HTTP method and headers
        }
      ).then(function(response) {
        return response.json();
      })
      .then(function(data) {
        self.items = data;
      });
    }
  }
};
</script>

Note: Apologies for any errors in my English.

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

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

Keep image height consistent and prevent resizing

I've hit a roadblock while trying to find a solution for this issue. There must be an easy fix that I'm overlooking... The problem arises when viewing the table with flags on a small screen (on mobile) - the image on the left seems to get sligh ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

Restricting specific devices and browsers access to my website

Is there an effective way to prevent outdated browser versions and mobile devices from accessing my website? I want to provide a message informing them of the compatible browsers for the site. ...

An error occurred while running JavaScript in Selenium WebDriver

static WebDriver driver = new FirefoxDriver(); public static void main(String[] args) throws IOException, InterruptedException { // TODO code application logic here BufferedReader br= new BufferedReader(new InputStreamReader(System.in) ...

Having trouble transferring file object from reactjs to nodejs

Hey there! I am relatively new to nodejs and React, and currently, I'm working on a project that involves sending a selected file from the front end (React) to the back end (Node). The goal is to upload the file and convert it into a JSON object. Howe ...

Mouse click not functioning as anticipated

<ul> <li> <a href='javascript:;' class='close'>close</a> <a>openId</a> </li> </ul> My goal is to delete the li element when the close link (a.close) is clicked. The li elements are genera ...

Creating personalized HTML tags using React.js

My goal may seem simple at first, but I keep running into a frustrating error from webpack. I want to render a custom tag in React, rather than using the standard tags. Here is the code that is causing me trouble: let htmlTag = "h" + ele.title.importance ...

Material-ui does not adjust Typography color based on the theme selected

Exploring material-ui, I have implemented two themes: const darkTheme = createMuiTheme({ palette: { type: "dark" } }); const lightTheme = createMuiTheme({ palette: { type: "light" } }); However, when utilizing the Typography component, t ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...

Issue with v-mask not being applied after data fetch in VUE.js

I recently started learning VUE.js and ran into a common beginner issue. After fetching some JSON data from a REST service and populating a v-model with the returned data, I noticed that the mask was not being applied correctly. However, when I manually ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

Implementing custom logic in a Vuetify dialog box

Is it possible to trigger a dialog on a button click while executing some logic before and after the event? How can this be accomplished? Here is what I have attempted: template <v-dialog v-model="dialog" width="400"> <template v-slot:activat ...

How can you ensure a div stays at the top or bottom of a page based on the user's scrolling behavior?

Hello there! While I know there have been many questions regarding sticking a div to the top or bottom while scrolling, my particular issue is a bit more specific. My dilemma is that I am looking for the div to stick either to the top or the bottom based ...

Utilizing a dropdown menu in HTML to dynamically alter the URL of a button using JavaScript

I attempted to search for a solution on stackoverflow, but I found the answers confusing. In essence, I am looking to create a list from which I can select a value that will change a link when clicking a button. I believe JavaScript is necessary for this ...

Adjust regex for image URLs in JavaScript to handle unique and special cases

Does anyone have experience with using image URL regular expressions to validate images in forms with the ng-pattern directive? I'm currently facing difficulties handling cases like https://google.com.png. Any assistance would be greatly appreciated. ...

Storing data efficiently with Angular 2's local storage service

I am attempting to create a ToDoList using localstorage within a service. add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } ...

Issue with Primeng 16: carousel styles failing to load properly

I am working on a straightforward project using Angular and Primeng 16. Currently, I have implemented a carousel, and everything seems to be working fine. However, when I try to navigate using the next or prev buttons, the information does not load. I ha ...

Unable to display cgi script results on webpage <div> with javascript

My goal is to display the output of a CGI script within a <div> on an HTML page using the following code: HTML <b>Already Loaded Data</b> <div id="result"></div> JS <script type="text/javascript" > var fdate=' ...