The button outside the vant component form triggers the submit event of the form form
Sometimes, according to the needs and layout requirements, the button button needs to be placed outside the form, but you want to trigger the submission event and also want to easily obtain the form value.
1. Add ref attribute to form form
<van-form ref="formData" alidate-first @submit="submit"> <van-field readonly v-model="name" name="name" label="Name" /> </van-form>
2. Handle external buttons
1. Add a click event to the button
<button type="submit" @click="send">External submission</button>
2. Processing logic within the click event
send(){ this.$(); },
Here formData is the ref attribute value on the form form form
Then you can click button and trigger the submit event of the form. In the future, you can directly write logic in the submit event
The complete code is attached:
<template> <div class="result"> <van-form ref="formData" alidate-first @submit="submit"> <van-field readonly v-model="name" name="name" label="Name" /> <van-field readonly v-model="idNumber" name="idNum" label="Identity card number" /> <van-field readonly v-model="phoneNumber" name="phone" label="Phone number" /> </van-form> <button type="submit" @click="send">External Submit Button</button> </div> </template>
<script> export default { data(){ return{ } }, methods:{ submit(values){ //The logic of submitting events (values) //values are the value of van-field in the form }, send(){ this.$(); }, } } </script> <style> </style>
Why does vant click on the normal button in the form trigger form submission
In the form, in addition to the submit button, there may be some other functional buttons, such as the send verification code button.
When using these buttons, be careful to set native-type to button, otherwise the form submission will be triggered.
<van-button native-type="button"> Send verification code </van-button>
The reason for this problem is that the default value of the button tag type property in the browser is submit, causing the form submission to be triggered.
We will adjust the default value of type to button in the next major version to avoid this problem.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.