This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

Button component, Dialog component, input component, switch component, radio component, radioGroup component, please contact us if you need them

Build Vue2 UI Component Library from 0 (1)

Build Vue2 UI Component Library from 0 (2)

Build Vue2 UI Component Library from 0 (3)

Build Vue2 UI Component Library from 0 (4)

Build Vue2 UI Component Library from 0 (5)

Build Vue2 UI Component Library from 0 (6)

How to encapsulate a Form component and a formItem component

Encapsulate the Form component

1. Parameter support

The parameter name The parameter types Parameters to describe The default value
model Object Collect form data There is no
labelWidth String The label width 80px

1.1. Get model, labelWidth properties, and custom content

  • Get the model and labelWidth properties passed in by the user using props. Since the Model property is required, set required:true for validation.
  • Use slots to get user – defined content.
  • Since the labelWidth attribute needs to be passed to the FormItem component to set the labelWidth, provide is used to distribute its component instance to descendant components so that descendant components can obtain the labelWidth attribute.
<template>
  <div class="zh-form">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "ZhForm".props: {
    model: {
      type: Object.required: true
    },
    labelWidth: {
      type: String.default: "80px"}},provide() {
    return {
      Form: this}; }};</script>
Copy the code

Encapsulate the formItem attribute

1. Parameter support

The parameter name The parameter types Parameters to describe The default value
label String The label An empty string

1.1. Set the label and labelWidth properties

  • Get the label attribute passed by the user using props.
  • Use slots to get user – defined content.
  • Receive component instance distributed by inject form component, obtain labelWidth to set labelWidth.
<template>
  <div class="zh-form-item">
    <label class="zh-form-item__label" :style="{width: this.Form.labelWidth}">{{label}}</label>
    <div class="zh-form-item__content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  name: "ZhFormItem".props: {
    label: {
      type: String.default: ""}},inject: ["Form"]};</script>
Copy the code