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



我正在使用Vuetify的v-form在Vue中使用他们的Composition API和<script setup>创建一个表单。使用v-form的规则,我创建了一种验证用户输入的方法;但是,一旦提交了表单,我就需要清除表单的字段。当字段被重置(使用空字符串)时,将触发表单规则并出现验证错误。我想访问v-form的内置函数(例如,clear());然而,我无法访问<script setup>中的this.$refs.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 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>

这是我的模板表单

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

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

<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()
....

相关内容

  • 没有找到相关文章

最新更新