继承父上下文的Vue.js组件:表单组代码封装实现
Here's how you can encapsulate that form group into a reusable Vue component that plays nicely with your parent context (including validation logic like determineError and VeeValidate's v-validate):
Step 1: Define the Reusable Component
We'll create a flexible component that accepts dynamic props for labels, validation rules, and more, while maintaining compatibility with Vue's v-model and parent-level error checking.
Vue.component('form-group', { props: { // Label text for the field label: { type: String, required: true }, // Field name (used for validation and input attribute) fieldName: { type: String, required: true }, // VeeValidate validation rules (e.g., 'required|min:5|max:100') validationRules: { type: String, required: true }, // Toggle mandatory asterisk display showMandatory: { type: Boolean, default: true }, // Current field value (for v-model sync) value: { required: true }, // Parent's error-checking function checkFieldError: { type: Function, required: true } }, template: ` <div class="form-group" :class="{'has-error': checkFieldError(fieldName)}"> <label>{{ label }}</label> <div class="mandat" v-if="showMandatory">*</div> <input :value="value" @input="$emit('input', $event.target.value)" :name="fieldName" v-validate="validationRules" class="form-control" > </div> ` })
Step 2: Use the Component in Your Parent
Replace your original form group code with this component, passing in the necessary props to sync with your parent's state and validation logic:
<form-group label="Content Label" field-name="content" validation-rules="'required|min:5|max:100'" v-model="form.content" :check-field-error="determineError" ></form-group>
Key Details:
- v-model Sync: By using the
valueprop and emittinginputevents, the component works just like a native input, keeping your parent's form data in sync. - Flexible Error Handling: Passing the parent's
determineErrorfunction as a prop ensures the component isn't tightly coupled to your parent's implementation—you can swap in any error-checking logic you need. - Reusability: This component can be reused across all your form fields, just update the props for label text, validation rules, and field name.
- VeeValidate Compatibility: Assuming VeeValidate is installed globally, the
v-validatedirective will work inside the component without extra setup.
If you need to support different input types (like textareas or selects) later, you can add a inputType prop or use a scoped slot to inject custom input elements while keeping the form group wrapper logic intact.
内容的提问来源于stack exchange,提问作者tzortzik

