vue之Form和FormItem组件的封装思想

在这里插入图片描述

Form.vue

<template>
  <div><slot></slot></div>
</template>

<script>
export default {
  name: "Form",
  props: {
    model: {
      type: Object,
      default() {
        return {};
      },
    },
    labelWidth: {
      type: String,
      default: "90px",
    },
  },
  // 向子组件 传递当前组件 this
  provide() {
    return {
      Form: this,
    };
  },
  data() {
    return {};
  },
};
</script>
<style  lang="scss" scoped>
</style>

FormItem.vue

<template>
  <div class="form-item">
    <label class="form-item-label" :style="{ width: this.Form.labelWidth }">
      {{ label }}
    </label>
    <div class="form-item-con">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "FormItem",
  props: {
    label: {
      type: String,
      default: "",
    },
  },
  inject: ["Form"],
  data() {
    return {};
  },
  methods: {},
};
</script>
<style  lang="scss" scoped>
.form-item {
  margin-bottom: 25px;
  .form-item-label {
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
  }
  .form-item-con {
    line-height: 40px;
    position: relative;
    font-style: 14px;
    overflow: hidden;
  }
}
</style>

使用组件

<template>
  <div class="home">
    model {{ model }}
    <x-from :model="model" labelWidth="80px">
      <x-form-item label="用户名">
        <x-input
          placeholder="请输入用户名:"
          v-model="model.username"
        ></x-input>
      </x-form-item>
      <x-form-item label="开关">
        <x-switch
          v-model="model.flag"
          activeColor="red"
          inActiveColor="green"
          name="username"
        ></x-switch>
      </x-form-item>
    </x-from>
  </div>
</template>

<script>
import XInput from "./Test/Input.vue";
import XSwitch from "./Test/Switch.vue";
import XFrom from "./Test/form/Form.vue";
import XFormItem from "./Test/form/FormItem.vue";
export default {
  name: "Home",
  components: {
    XFrom,
    XFormItem,
  },
  data() {
    return {
      // form 绑定的数据
      model: {
        username: "",
        flag: false,
      },
    };
  },
};
</script>
<style lang="scss" scoped>
.home {
  height: calc(100% - 34px);
  width: calc(100% - 34px);
  background: #fff;
  padding: 16px;
  border: 1px solid #ccc;
}
</style>

Logo

前往低代码交流专区

更多推荐