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

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值