使用Vue Composition API写出清晰、可扩展的表单实现(3)

export default function (startVal, validators, onValidate) { const input = ref(startVal); const errors = ref([]); watch(input, value => { errors.value = validators.map(validator => validator(value)); onValidate(value); }); return { input, errors } }

最后回到 InputName 组件,现在将为 useInputValidator 方法提供必需的三个参数。
第二个参数现在是一个验证器数组,因此让我们在适当的地方声明一个数组,并传入 minLength 方法。

minLength 是一个工厂函数,调用并传递指定的最小长度。

现在我们还从合成函数返回的对象获取 input 和 errors,它们都将从 setup 方法返回,以便在组件中可用。

src/components/InputName.vue

// 省略其他代码 ... import { minLength } from "@/validators"; import useInputValidator from "@/features/useInputValidator"; export default { ... setup (props, { emit }) { const { input, errors } = useInputValidator( props.value, [ minLength(3) ], value => emit("input", value) ); return { input, errors } } }

这是我们将添加到该组件的最后一个功能。在我们继续之前,花点时间对比一下这段代码比使用mixin可读性强得多。

首先,可以清楚地看到状态变量在哪里声明和修改,而不必切换到单独的 mixin 模块文件。另外,不需要担心局部变量和复合函数之间的名称冲突。

显示错误

进入 InputName 组件的模板,有潜在的错误数组要显示,将其委托给一个称为 ErrorDisplay 的组件来显示错误。

src/components/InputName.vue

<template> <div> <label> Name <input type="text" v-model="input" /> </label> <ErrorDisplay :errors="errors" /> </div> </template> <script> ... import ErrorDisplay from "@/components/ErrorDisplay"; export default: { ... components: { ErrorDisplay } } </script>

ErrorDisplay 组件根据业务需要,可以自己定制。

重用代码

这就是我们基于Composition API 写的表单的基本功能。本教程的目标是创建清晰且可扩展的表单代码,通过定义 InputEmail 组件,来证明我们已经做到了这一点。

src/components/InputEmail

<template> <div> <label> Email <input type="email" v-model="input" /> </label> <ErrorDisplay v-if="input" :errors="errors" /> </div> </template> <script> import useInputValidator from "@/features/useInputValidator"; import { isEmail } from "@/validators"; import ErrorDisplay from "./ErrorDisplay"; export default { name: "InputEmail", props: { value: String }, setup (props, { emit }) { const { input, errors } = useInputValidator( props.value, [ isEmail() ], value => emit("input", value) ); return { input, errors } }, components: { ErrorDisplay } } </script>

原文:https://vuejsdevelopers.com/2020/03/31/vue-js-form-composition-api/
参考:https://css-tricks.com/how-the-vue-composition-api-replaces-vue-mixins/

到此这篇关于使用Vue Composition API写出清晰、可扩展的表单实现的文章就介绍到这了,更多相关Vue Composition API清晰、可扩展的表单内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/88e0513d2b183ccefe64e12f5c9a81b0.html