首页 > 解决方案 > 表单 $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

标签: vue.jsvuetify.jsnuxt.js

解决方案


这对我有用

<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>

推荐阅读