如何使用 <script setup> 中的 Composition API 访问 VueJS 中的 Vuetify v-form ref?

Bra*_*enK 7 typescript vue.js vuetify.js vuejs3 vuetifyjs3

我正在使用v-formVue 中的 Vuetify 使用他们的 Composition API 和<script setup>. 使用v-form的规则,我创建了一种验证用户输入的方法;但是,提交表单后,我需要清除表单的字段。当重置字段(使用空字符串)时,会触发表单规则并出现验证错误。我想访问 的v-form内置函数(例如clear());但是,我无法this.$refs.form访问<script setup>. 如何访问这些功能或仅清除表单而不在提交后触发验证规则错误?

这是到目前为止的脚本部分:

<script setup lang="ts">
import { ref, Ref } from 'vue'
import { Service } from '@/types/service'

const service: Ref<Service> = ref({ name: '', endpoint: '' })
const loading = ref(false)
const isValid = ref(true)

const register = () => {
  loading.value = true
  isValid.value = false
  clear()
  setTimeout(() => {
    loading.value = false
  }, 2000)
}

const clear = () => {
  service.value = { name: '', endpoint: '' }
}

const serviceNameRules = [
  (v: string) => !!v || 'Service name is required',
  (v: string) =>
    v.length <= 20 || 'Service name must be less than 20 characters',
]

const endpointRules = [
  (v: string) => v.length <= 100 || 'Endpoint must be less than 100 characters',
  (v: string) =>
    isURL(v) ||
    'Endpoint must have a valid URL format (i.e., "http://example.com")',
]

const isURL = (str: string) => {
  try {
    const url = new URL(str)
    return url.protocol === 'http:' || url.protocol === 'https:'
  } catch (_) {
    return false
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

这是我的模板表格

<template>
  <v-card elevation="5">
    <v-progress-linear
      v-if="loading"
      class="position-absolute"
      style="z-index: 1"
      color="#0062B8"
      height="10"
      indeterminate
    />

    <v-card-title>Register New Service</v-card-title>
    <v-card-text>
      <v-form
        @submit.prevent="register()"
        v-model="isValid"
        ref="form"
        lazy-validation
      >
        <v-text-field
          v-model="service.name"
          label="Service Name"
          hint="e.g., 'service-pages'"
          :rules="serviceNameRules"
          required
        />
        <v-text-field
          v-model="service.endpoint"
          label="Endpoint"
          hint="https://www.example.com/page"
          :rules="endpointRules"
          required
        />
        <v-btn
          type="submit"
          color="#0062B8"
          style="color: white"
          :disabled="!isValid"
        >
          Register
        </v-btn>
      </v-form>
    </v-card-text>
  </v-card>
</template>
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 5

尝试form在脚本中创建一个自动绑定到的引用ref="form":

<script setup lang="ts">
import { ref, Ref } from 'vue'
import { Service } from '@/types/service'

const service: Ref<Service> = ref({ name: '', endpoint: '' })
const loading = ref(false)
const isValid = ref(true)

const form=ref<HTMLFormElement>(null)

....
 // then use it like 
 if(form.value){
     form.value.reset()
  }
 //or
  form.value?.reset()
....

Run Code Online (Sandbox Code Playgroud)