Eyal
Eyal

Reputation: 4773

Bind a @click event to href in Array

I have the following code which I am using to populate a datatable. For each row in the datatable, I have an update link. clicking the update should call the ShowModal() method.

How can I call ShowModal() from this <a>?

   <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>`  // I was trying this...        
               ]);

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

           });
         }

Upvotes: 1

Views: 118

Answers (1)

webmint
webmint

Reputation: 219

I think what u are trying to do its not Vue way, but JQuery way. So let me propose to u more correct code (IMHO)

<template>
     <table id="buildings" class="mdl-data-table" width="100%">
        <tr
            v-for="(item, index) in dataset"
            :key=(index) // or building id if u like
        >
            <td>{{ item.buildingId }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.city }}</td>
            <td
                @click="showModal(item.buildingId)"
            >
            click me! A not required here. U can use div if u want to have not 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 suppose u have as responce here array of objects?
                this.dataset = response.data
            })
            .catch(e => console.warn(e));
        }

Upvotes: 1

Related Questions