我使用:- "vue":"3.2.26",-“vee-验证”:"4.5.6",-“类型记录”:"4.5.4“
在vue3上创建textarea字段时,遇到了一个问题
我有过
使用vee验证的示例
import { Field, useForm } from 'vee-validate'
<Field v-slot="{ field, errors }" name="name" type="text">
<VControl icon="feather:edit-2" :has-error="Boolean(formErrors.name)">
<input
v-bind="field"
class="input is-primary-focus"
type="text"
placeholder="Placeholder"
autocomplete="name"
/>
<p v-if="errors" class="help is-danger">{{ formErrors.name}}</p>
</VControl>
</Field>简单例子
<textarea
v-model="fieldValues.description"
class="textarea is-success-focus"
rows="3"
placeholder="Description"
></textarea>为模型
export interface iCat {
id: number
name: string
description: string | null
}但是文本区域返回错误
Type 'null' is not assignable to type 'string | number | string[] | undefined'.用于验证
const {
values: fieldValues,
errors: formErrors,
handleSubmit,
} = useForm({
initialValues: {
id: 0,
name: '',
description: ''
},
validationSchema: object({
id: number().required().integer(),
name: string().required(),
description: string().notRequired().default(null).nullable()
}),
})如果选中@vue/运行时-dom/dist/运行时-dom.d.ts
export interface TextareaHTMLAttributes extends HTMLAttributes {
....
value?: string | string[] | number
...
}如果我查看节点-模块,我会发现textarea不接受null作为值--那么我如何正确地解决这个问题呢?
发布于 2022-03-11 01:35:58
不幸的是,您不能为TextareaHTMLAttributes更改现有类型的TextareaHTMLAttributes(至少在TypeScript 4.5.5中不是这样)。类型增强只允许扩展(向类型添加属性,或者创建一个新类型来扩展原始TextareaHTMLAttributes接口,并为value创建新类型)。
解决方法是使用扩展iCat的新类型,将其description类型更改为预期的TextareaHTMLAttributes's value类型。
"iFieldValues"),使用Omit从iCat中排除原始description属性,并声明一个具有新description属性(具有TextareaHTMLAttributes['value']类型)的交叉点。values上使用values (as iFieldValues)。// MyForm.vue
<script setup lang="ts">
import { toRefs } from 'vue'
import type { TextareaHTMLAttributes } from '@vue/runtime-dom'
import { useForm } from 'vee-validate'
import { object, number, string } from 'yup'
export interface iCat {
id: number
name: string
description: string | null
}
1️⃣
type iFieldValues = Omit<iCat, 'description'> & {
description: TextareaHTMLAttributes['value']
}
const {
values,
errors: formErrors,
handleSubmit,
} = useForm({
initialValues: {
id: 0,
name: '',
description: ''
},
validationSchema: object({
id: number().required().integer(),
name: string().required(),
description: string().notRequired().default(null).nullable()
}),
})
2️⃣
const fieldValues = values as iFieldValues
</script>https://stackoverflow.com/questions/71423906
复制相似问题