简体   繁体   English

Vue - 我如何传递按钮值以提交表单?

[英]Vue - how can i pass button value to submit in form?

I created a Vue form where there are two buttons.我创建了一个 Vue 表单,其中有两个按钮。 In my formSubmit() function i need to somehow find which button was used to submit the form.在我的formSubmit() function 中,我需要以某种方式找到用于提交表单的按钮。 Here is what i tried:这是我尝试过的:

<form @submit.prevent="formSubmit()">
  <input type="text" class="form-control" v-model="name">
  <input type="text" class="form-control" v-model="product">
  <button class="btn btn-primary" v-model="buttonType" value="button1">BUTTON1</button>
  <button class="btn btn-primary" v-model="buttonType" value="button2">BUTTON2</button>
</form>

And my function:还有我的 function:

formSubmit(){
  console.log(this.buttonType)
}

But once i click the button, i always get an undefined .但是一旦我点击按钮,我总是得到一个undefined Is there any other way to get the button used to submit the form?有没有其他方法可以获取用于提交表单的按钮? Any advice is appreciated.任何建议表示赞赏。

You shouldn't really use v-model on a <button> element.您不应该真正在<button>元素上使用v-model

You can register separate event handlers for each button and call submit your form at the event of the respective event handlers.您可以为每个按钮注册单独的事件处理程序,并在相应事件处理程序发生时调用提交表单。

<form @submit.prevent="onFormSubmit">
  <button @click="onClickButton1">Button 1</button>
  <button @click="onClickButton2">Button 2</button>
</form>
{
  // ...
  methods: {
    onFormSubmit() {},
    onClickButton1() {
      // code for when button 1 is pressed
      this.onFormSubmit()
    },
    onClickButton2() {
      // code for when button 2 is pressed
      this.onFormSubmit()
    },
  },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM