jooscher
jooscher

Reputation: 25

How can i delete a certain row from a table in VueJS

I am trying to delete a certain element from an array, that I display in a HTML-Table.

Here's the frontend:

HTML-table_frontend

I push the Data from the input into an array userData. The HTML-Table is build within a v-forloop in VUEjs. Upon Pressing a button, I want the dedicated function (e.g. deleteData()) to only be applied to the row that that button is in. How can I tell the button what Array-Index it needs to target?

Here's the code snippets:

Table:

<table id="userData">
    <tr>
        <th>Name</th>
        <th>Email Address</th>
        <th>Mobile Number</th>
        <th>Action</th>
    </tr>
<tr v-for="(userData, k) in userData" :key="k">  
     <td class="name">
        <input readonly class="tableDisplay" type="text" v-model="userData.name" />
    </td>
     <td>
        <input readonly class="tableDisplay" type="email" v-model="userData.email" />
    </td>
     <td>
        <input readonly class="tableDisplay" type="number" v-model="userData.number" />
    </td>
     <td>
        <button type='button' class="buttonRead"  @click="readData" >Read</button>
        <button type='button' class="buttonEdit" @click="editData">Edit</button>
        <button type='button' class="buttonDelete" @click="deleteData">Delete</button>
    </td>
</tr>
</table>

Javascript in the .vue:

<script>
export default {
    data() {
        return{
            
            userData:[],

            newUser: {
                name: '',
                email:'',
                number:''
            }
        };
    },
    methods: {
       
        customSubmit(){
            
            
                this.userData.push(this.newUser)
                this.newUser = {
                    name:'',
                    email:'',
                    number:''
                }
                console.log(this.userData)   
        

        },

      

        
    }
    
}
</script>

Upvotes: 1

Views: 1567

Answers (1)

Alan Millirud
Alan Millirud

Reputation: 1172

example with passing index

<button type='button' class="buttonDelete" @click="deleteData(k)">Delete</button>

methods: {
  deleteData(k) {
     this.userData.splice(k, 1)
   }
}

or passing object

<button type='button' class="buttonDelete" @click="deleteData(userData)">Delete</button>

methods: {
  deleteData(userData) {
     let index = this.userData.indexOf(userData)
     this.userData.splice(index, 1)
   }
}

UPD. readData

<button type='button' class="buttonRead"  @click="readData(k)" >Read</button>

methods: {
  readData (k) {
      console.log(this.userData[k].name)
    },
}

also change userData variable name

<tr v-for="(rowUser, k) in userData" :key="k"> 

in inputs

<input  ... v-model="rowUser.name" />

live example https://jsfiddle.net/8v2cx4je/

Upvotes: 4

Related Questions