Wrapping and Reusing Components
🎯 Introduction
Wrapping and reusing components is an essential frontend skill. Wrapping Element UI components reduces repeated code, keeps interfaces consistent, and improves maintainability and extensibility. This article walks through creating reusable dialog, input, and select components.
🔧 Why Wrap Components?
Projects often reuse dialogs, inputs, and dropdowns. Repeating their logic and styling takes time and introduces errors. Wrappers offer several benefits:
- Reuse logic instead of implementing it repeatedly.
- Keep styles consistent across the UI.
- Simplify maintenance: one change updates every instance.
- Support flexible customization through slots and event callbacks.
💬 Wrapping a Dialog
Element UI’s el-dialog is a flexible dialog component. A wrapper makes it easy to create dialogs with shared configuration.
1. Define Common Props
Common options include the title, width, and footer button labels. Here is a basic MyDialog wrapper:
<template>
<el-dialog :title="title" :visible.sync="visible" :width="width" @close="handleClose">
<slot></slot>
<span slot="footer" class="dialog-footer">
<el-button @click="handleCancel">{{ cancelText }}</el-button>
<el-button type="primary" @click="handleConfirm">{{ confirmText }}</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: 'MyDialog',
model: {
prop: 'value',
event: 'update:value',
},
props: {
value: {
type: String,
default: '',
},
title: {
type: String,
default: 'Confirmation',
},
width: {
type: String,
default: '50%',
},
confirmText: {
type: String,
default: 'Confirm',
},
cancelText: {
type: String,
default: 'Cancel',
},
},
computed: {
visible: {
get() {
return this.value;
},
set(val) {
this.$emit('update:value', val);
},
},
},
methods: {
handleConfirm() {
this.$emit('confirm');
},
handleCancel() {
this.$emit('cancel');
this.$emit('update:value', false);
},
handleClose() {
this.$emit('close');
},
},
};
</script>
2. Usage Example
<template>
<div>
<el-button @click="showDialog = true">Open dialog</el-button>
<my-dialog
v-model="showDialog"
title="Custom title"
width="60%"
confirmText="Confirm"
cancelText="Close"
@confirm="onConfirm"
@cancel="onCancel"
>
<p>This is the dialog content. You can put any content here.</p>
</my-dialog>
</div>
</template>
<script>
import MyDialog from './MyDialog.vue';
export default {
components: { MyDialog },
data() {
return {
showDialog: false,
};
},
methods: {
onConfirm() {
this.$message.success('Confirm clicked!');
this.showDialog = false;
},
onCancel() {
this.$message.info('Cancel clicked!');
},
},
};
</script>
📝 Wrapping an Input
Inputs are among the most common form controls. Element UI’s el-input provides many props and events. A wrapper can add validation, length limits, and consistent styling.
1. Basic Wrapper
Create a MyInput component:
<template>
<el-form-item :label="label" :prop="prop" :rules="rules">
<el-input
v-model="innerValue"
:placeholder="placeholder"
:maxlength="maxlength"
show-word-limit
/>
</el-form-item>
</template>
<script>
export default {
name: 'MyInput',
model: {
prop: 'value',
event: 'update:value',
},
props: {
value: {
type: String,
default: '',
},
label: {
type: String,
default: '',
},
placeholder: {
type: String,
default: 'Enter text',
},
prop: {
type: String,
default: '',
},
rules: {
type: Array,
default: () => [],
},
maxlength: {
type: Number,
default: 50,
},
},
computed: {
innerValue: {
get() {
return this.value;
},
set(val) {
this.$emit('update:value', val);
},
},
},
};
</script>
<style scoped>
.el-input {
width: 100%;
}
</style>
2. Usage Example
<template>
<el-form :model="form" :rules="rules" ref="formRef">
<my-input
v-model="form.username"
label="Username"
prop="username"
:rules="rules.username"
:maxlength="20"
/>
<el-button type="primary" @click="submitForm">Submit</el-button>
</el-form>
</template>
<script>
import MyInput from './MyInput.vue';
export default {
components: { MyInput },
data() {
return {
form: {
username: '',
},
rules: {
username: [
{
required: true,
message: 'Enter a username',
trigger: 'blur',
},
{
min: 3,
max: 20,
message: 'Use 3 to 20 characters',
trigger: 'blur',
},
],
},
};
},
methods: {
submitForm() {
this.$refs.formRef.validate(valid => {
if (valid) {
this.$message.success('Submitted successfully!');
}
});
},
},
};
</script>
prop on el-form-item identifies the field associated with its validation rules. Combining an input wrapper with Element UI’s validation system simplifies form development.🎯 Wrapping a Select
Select controls are common in application interfaces, including dropdowns and multiple selects. Element UI provides several selection components; here, we will wrap a basic single-select dropdown.
1. Basic Wrapper
Create a MySelect wrapper.
<template>
<el-form-item :label="label" :prop="prop" :rules="rules">
<el-select v-model="innerValue" :placeholder="placeholder" @change="onChange">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
</template>
<script>
export default {
name: 'MySelect',
model: {
prop: 'value',
event: 'update:value',
},
props: {
value: {
required: true,
},
label: {
type: String,
default: '',
},
prop: {
type: String,
default: '',
},
rules: {
type: Array,
default: () => [],
},
placeholder: {
type: String,
default: 'Select an option',
},
options: {
type: Array,
default: () => [],
},
},
computed: {
innerValue: {
get() {
return this.value;
},
set(val) {
this.$emit('update:value', val);
},
},
},
methods: {
onChange(val) {
this.$emit('input', val);
this.$emit('change', val);
},
},
};
</script>
<style scoped>
.el-select {
width: 100%;
}
</style>
2. Usage Example
<template>
<el-form :model="form" :rules="rules" ref="formRef">
<my-select
v-model="form.gender"
label="Gender"
prop="gender"
:options="genderOptions"
:rules="rules.gender"
/>
<el-button type="primary" @click="submitForm">Submit</el-button>
</el-form>
</template>
<script>
import MySelect from './MySelect.vue';
export default {
components: { MySelect },
data() {
return {
form: {
gender: '',
},
genderOptions: [
{ label: 'Male', value: 'male' },
{ label: 'Female', value: 'female' },
],
rules: {
gender: [
{
required: true,
message: 'Select a gender',
trigger: 'change',
},
],
},
};
},
methods: {
submitForm() {
this.$refs.formRef.validate(valid => {
if (valid) {
this.$message.success('Submitted successfully!');
}
});
},
},
};
</script>
options to keep the wrapper reusable, and expose a change event for application-specific behavior.❓ Questions and Answers
Q1: Why bind a dialog’s visible prop with .sync?
The .sync modifier keeps parent and child state synchronized. When the dialog emits update:visible, the parent’s visibility value updates as well, keeping opening and closing in sync.
Q2: How can an input wrapper use shared validation rules?
Pass shared rules through the rules prop on el-form or el-form-item. The input wrapper forwards prop and rules so Element UI can validate the field.
🧪 Exercises
Exercise 1
Extend the dialog wrapper with a custom footer button whose label and event handler are supplied by the parent.
<template>
<my-dialog :visible.sync="visible" title="Dialog with multiple buttons" @confirm="onConfirm" @cancel="onCancel">
<p>Content area</p>
<template v-slot:footer>
<!-- Custom button area -->
</template>
</my-dialog>
</template>
<script>
export default {
data() {
return { visible: false };
},
methods: {
onConfirm() {
/* Handle confirmation */
},
onCancel() {
/* Handle cancellation */
},
},
};
</script>
Exercise 2
Create a multiple-select wrapper that accepts options and returns an array of selected values.
<template>
<el-select v-model="innerValue" multiple :placeholder="placeholder" @change="onChange">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<script>
export default {
props: {
/* ... */
},
data() {
/* ... */
},
methods: {
/* ... */
},
};
</script>
🎉 You now know how to wrap Element UI components, use slots, and integrate form validation!
