Attach an @click event to the href attributes within an array

I am currently working on code to populate a datatable with rows. Each row in the datatable contains an update link, which when clicked should trigger the ShowModal() method.

How can I invoke the ShowModal() function using this <a> element?

   <template>
     <table id="buildings" class="mdl-data-table" width="100%"></table>
    </template>

    methods: {
        ShowModal(buildingId){
          // do something here...
        }, 
        listBuildings() {                      
         axios
            .get("https://localhost:44349/api/Building/List", headers)
            .then(response => {
              response.data.forEach(el => {            
                this.dataset.push([
                  el.buildingId,
                  el.projectName,
                  el.city,                 
                  `<a click='${this.ShowModal(el.buildingId)}'>Update</a>`  // Trying to make this work         
               ]);

            $("#buildings").DataTable({
                  data: this.dataset});

           });
         }

Answer №1

It seems like the approach you're taking is more in line with JQuery rather than Vue. Allow me to suggest a more appropriate code snippet for you (in my humble opinion).

<template>
     <table id="buildings" class="mdl-data-table" width="100%">
        <tr
            v-for="(item, index) in dataset"
            :key=(index) // or building id if you prefer
        >
            <td>{{ item.buildingId }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.city }}</td>
            <td
                @click="showModal(item.buildingId)"
            >
            click me! A not required here. You can use div if you want to have a non-cell clicked and style it with CSS
            </td>
        </tr>
     </table>
</template>

methods: {
    showModal(buildingId){
      // do something here...
    }, 
    listBuildings() {                      
     axios
        .get("https://localhost:44349/api/Building/List", headers)
        .then(response => {
            // I assume you receive an array of objects as the response here?
            this.dataset = response.data
        })
        .catch(e => console.warn(e));
    }

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

My Javascript file in AngularJS is giving me trouble with the error message: "Uncaught Error: [$injector:modulerr]"

I am currently enrolled in an AngularJS course and the instructor is using version 1.0.8, while I have version 1.7.8 installed. I would like to update my version. Can anyone provide guidance on how to do this? File: index.html <!doctype html> <h ...

Modify the colors of multiple texts using a concise code block of fewer than 20 lines

I have 8 paragraphs and I want to toggle the class 'one-active' when clicking on each of them, while removing the active class from the others. I currently have the code working for two paragraphs, but it's too lengthy for all eight. How can ...

Exploring the process of transferring a variable from Frontend to Backend via a GET API in ReactJS with an Express API

When working with my freight Shipment table, I need to access the email of the logged-in user in order to perform some frontend tasks. However, I am struggling to retrieve this information using the Axios.get() method and use it to query my MySQL DB. In t ...

How can I show the table row as an inner table row when the first field is identical?

<tr ng-model="check" ng-repeat="orderBook in orderBookDetails| orderBy: 'orderBook.no'" value='check=$scope.orderBookDetails.sowNo'> <td ng-if='check!=orderBook.no'>{{orderBook.no}}</td> <td>{{order ...

Ways to troubleshoot issues that arise when updating the node version

After upgrading my version, I encountered a serious error. I developed a program a few years ago using version 18.x. Now that I have upgraded node.js, I am facing some errors. Below are the error messages: ERROR in ./app/assets/scss/styles.scss (./node_mo ...

The body tag mysteriously disappears after the function is called within the $().html() command

As I delve into scraping the source code of a website, I encounter an interesting phenomenon. Initially, when I print out the complete source code, everything appears as expected. However, upon attempting to print an actual DOM, I notice a slight change i ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Revamp the state within a React component

I created a component that organizes logos within a grid system. The component receives 2 props: grid (which contains the logos) and limit (indicating the number of logos to be displayed). type Props = { grid: [], limit: number, }; type Sta ...

What steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: 'use strict'; var Comment = require('../../../models/comment'); module.exports = { description: 'Create a Comment', notes: 'Create a comment&apos ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Tips for swapping out an item mid-scrolling?

What is the best way to change the navbar when scrolling a page in React? How can I achieve this while following React's concepts? Is using getElementById considered bad practice? const useState = React.useState const useEffect = React.useEffect con ...

Utilize $http.get within a service/factory to retrieve a set of items

I am trying to utilize a http.get promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller... My query is regarding the proper usage of $http.get() in a service to fetch and modify t ...

Using javascript to locate and substitute a word divided among multiple tags - a step-by-step guide

I need to utilize JavaScript to locate and substitute a word that has been separated into multiple tags. For instance, consider the following HTML code: <html> <body> <div id="page-container"> This is an apple. ...

Trigger the submission of Rails form upon a change in the selected value within a dropdown form

I am working on a Rails application that has a table of leads. Within one of the columns, I display the lead's status in a drop-down menu. My goal is to allow users to change the lead's status by simply selecting a different value from the drop-d ...

Guide on converting JSON encoded data into a JavaScript array

I have a few web pages that display results in the following format: [{"id":"1","company":"Gaurishankar","bus_no":"JHA 12 KH 1230"}, {"id":"2","company":"Gaurishankar","bus_no":"BA 2 KH 2270"}] Now, I want to take this JSON encoded data and use it in a J ...

What is the process for uploading SVG files created by users onto the server?

After dedicating three full days to researching, I have hit a roadblock in my attempts to allow users to upload SVG files to the server on my website. I created an HTML and Javascript platform where users can input dimensions into a form to create a basic ...

What is the process for importing Progressbar.js into a Laravel project?

I am attempting to implement a progress bar in Laravel 5.6 using this specific progress bar library. The Progress.js documentation indicates that the following steps are necessary: var ProgressBar = require('progressbar.js') Within the default ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Encountering a Type Error while attempting to display items from an array

Encountering an issue while attempting to load quiz questions from a db.json server. The error message reads: "TypeError: this.state.questions[this.state.currentQuestion] is undefined". In order to provide more context, here's a link to a sandbox of m ...