Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vue.js - 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?

question from:https://stackoverflow.com/questions/65833126/call-different-methods-for-form-with-multiple-buttons-using-vue

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...