vue.js - 表单 $ref 在方法内部未定义?
问题描述
我有一个非常简单的 Vuetify 表单,带有ref="form"
. 当我按下提交时,我想验证并以编程方式提交表单,但是由于某种原因this.$refs.form
返回未定义。
我几乎希望它像一个错字一样愚蠢,因为这看起来很简单!
<template>
<v-form
v-if="!submitted"
ref="form"
v-model="valid"
name="contactForm"
data-netlify="true"
data-netlify-honeypot="bot-field"
method="POST"
@submit.prevent="submit">
<input
type="hidden"
name="form-name"
value="contactForm">
...input fields
<v-row justify="center">
<v-col
sm="12"
class="text-center">
<v-btn
:disabled="!valid || sendingForm"
color="accent"
depressed
:ripple="false"
x-large
type="submit">
{{ sendingForm ? 'Loading...' : 'Submit' }}
</v-btn>
</v-col>
</v-row>
<p class="d-none">
<label for="bot-field">Don't fill this out: </label>
<input
type="text"
name="bot-field">
</p>
</v-form>
</template>
<script>
export default {
methods: {
async submit() {
this.sendingForm = true;
console.log('refs: ', this.$refs); <-- returns undefined for this.$refs.form
if (this.$refs.form.validate()) {
console.log('refs: ', this.$refs); <-- also returns undefined for this.$refs.form
this.$refs.form.submit();
this.submitted = true;
}
this.sendingForm = false;
}
},
}
</script>
我已经尝试删除v-if
表单上的,删除按钮上的type="submit
/添加,从表单中删除......似乎没有任何工作!有没有人遇到过这样的事情?谢谢!@click="submit
@submit.prevent="submit
解决方案
这对我有用
<v-form
ref="form"
v-model="valid"
name="contactform1"
action="/contact"
method="post"
data-netlify="true"
netlify-honeypot="bot-field"
>
<input type="hidden" name="form-name" value="contactform1" />
<v-row class="spacing6">
<v-col cols="12" sm="6" class="pa-6">
<v-text-field
v-model="name"
:rules="nameRules"
:label="$t('common.form_name')"
class="input"
name="name"
required
/>
</v-col>
<v-col cols="12" sm="6" class="pa-6">
<v-text-field
v-model="email"
:rules="emailRules"
:label="$t('common.form_email')"
class="input"
name="email"
required
/>
</v-col>
</v-row>
<div class="btn-area">
<div class="form-control-label">
<v-checkbox
v-model="checkbox"
color="primary"
:rules="[v => !!v || 'You must agree to continue!']"
:label="$t('common.form_terms')"
required
/>
<a href="#">{{ $t('common.form_privacy') }}</a>
</div>
<v-btn
color="primary"
outlined
@click="validate"
large
type="submit"
value="Send message"
>
{{ $t('common.form_send') }}
<v-icon class="right-icon">mdi-send</v-icon>
</v-btn>
</div>
</v-form>
推荐阅读
- flutter - 如何通过 Dart 中的 onTap 函数将值传递到另一个屏幕?
- angular - Angular *ngIf 不能与 ng-template 一起使用
- reactjs - react.js 错误**在现有状态转换期间无法更新**
- javascript - 使用 javascript 从本地存储中删除匹配的密钥对象
- php - WPBakery Page Builder 扩展交互式文本
- html - 在背景图像上移动表格时遇到问题
- opencv - 磨损碎片图像处理
- spring-boot - 调用 Azure Vision API 时出现 SSL/TLS 握手错误
- batch-file - 如何在批处理脚本中文件名的最后 6 位之前附加符号?
- azure - Azure CLI - az storage file delete-batch:除一个特定文件外的所有模式