BoundForGlory
BoundForGlory

Reputation: 4417

Call different methods for form with multiple buttons using Vue

I have a form with more than one button:

<form action="#" @submit.prevent="submit">
<div class="col-md-8 offset-md-4">
              <button class="btn btn-danger marginme" >Delete</button>
              <button type="submit" @click="submit" class="btn btn-primary">Update</button>
 </div>

When I click either button, the submit function is called twice (once for each button). What I want to do is call a delete function when delete is clicked, update when the update button is clicked.

I've tried this:

   <form action="#" @submit.prevent="submit">
  <div class="col-md-8 offset-md-4">
          <button type="submit" @click="submit('delete')" class="btn btn-danger marginme" >Delete</button>
          <button type="submit" @click="submit('update')" class="btn btn-primary">Update</button>
  </div>

and in my scripts, the submit method is this:

 export default {
methods:{
       async submit(action) {
    if (action=== "delete"){
       this.$alert('delete is called, update should not');
     return;
    }else{
       this.$alert('update is called, delete should not');
     }
  },
}

This approach, the action parameter is populated BUT, submit is still called twice. Once for each button, so the delete and update code are being ran instead of just one or the other. How do i make the form submit only once when either button is clicked on my form?

Upvotes: 1

Views: 4096

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Just remove the handler from form submit event and keep it like <form action="#" @submit.prevent=""> because the handler submit is called by the button click event and the form submit event

then pass the action name as parameter as you did :

  <form action="#" @submit.prevent="">
  <div class="col-md-8 offset-md-4">
          <button type="submit" @click="submit('delete')" class="btn btn-danger marginme" >Delete</button>
          <button type="submit" @click="submit('update')" class="btn btn-primary">Update</button>
  </div>

Upvotes: 3

zcoop98
zcoop98

Reputation: 3089

If you don't plan to use the features of the <form> element to submit or trigger some other action, you can simply do away with it and use separate methods with your button @click's, which should fix any of the double actions you're seeing.

<template>
  <!-- Do away with the form: form action="#" @submit.prevent="submit" -->
  <div class="col-md-8 offset-md-4">
    <button class="btn btn-danger marginme" @click="delete">
      Delete
    </button>
    <button class="btn btn-primary" @click="update">
      Update
    </button>
  </div>
</template>

<script>
export default {
  methods: {
    async delete() {
      this.$alert('delete is called, update should not');
    },
    async update() {
      this.$alert('update is called, delete should not');
    },
  },
}
</script>

Upvotes: 2

Related Questions