从0搭建Vue2 UI组件库(七)

这是我参与8月更文挑战的第22天,活动详情查看:8月更文挑战

前面写了封装button组件、dialog组件、input组件、switch组件、radio组件、radioGroup组件,有需要的童鞋请冲~~

从0搭建Vue2 UI组件库(一)

从0搭建Vue2 UI组件库(二)

从0搭建Vue2 UI组件库(三)

从0搭建Vue2 UI组件库(四)

从0搭建Vue2 UI组件库(五)

从0搭建Vue2 UI组件库(六)

这篇来写下如何封装form组件和formItem组件~~~

一、封装form组件

1. 参数支持

参数名称 参数类型 参数描述 默认值
model Object 收集表单数据
labelWidth String label宽度 80px

1.1. 获取model、labelWidth属性和自定义内容

  • 使用props获取用户传入的model、labelWidth属性。由于model属性是必须要有的,所以校验时需设置required:true。
  • 使用插槽获取用户的自定义内容。
  • 由于labelWidth属性需要传递给FormItem组件设置标签宽度,所以用provide分发自身组件实例给后代组件,以便后代组件获取labelWidth属性。
<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>
复制代码

二、封装formItem属性

1. 参数支持

参数名称 参数类型 参数描述 默认值
label String 标签 空字符串

1.1.设置label、labelWidth属性

  • 使用props获取用户传入的label属性。
  • 使用插槽获取用户的自定义内容。
  • 用inject接收form组件分发的组件实例,取得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>
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享