iview通过select勾选动态生成表单的demo

陌路散爱 提交于 2020-08-11 05:56:54
<template>
  <div id="app">
    <Select v-model="model" style="width:200px" @on-change="selectChange" label-in-value>
      <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
    </Select>
    <Button type="dashed" @click="handleAdd" icon="md-add">Add item</Button>
    <Form ref="formDynamic" :model="formDynamicConfig" :label-width="80" style="width: 300px">
      <transition-group name="fades">
        <FormItem v-for="(item, index) in formDynamic" :key="item.value" :label="item.label">
          <Row>
            <Col span="18">
              <Input
                type="text"
                v-model="formDynamicConfig[item.value]"
                placeholder="Enter something..."
              ></Input>
            </Col>
            <Col span="4" offset="1">
              <Button @click="handleRemove(item,index)">Delete</Button>
            </Col>
          </Row>
        </FormItem>
      </transition-group>
    </Form>
    {{formDynamicConfig}}
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      cityList: [
        {
          value: "projName",
          label: "项目名称"
        },
        {
          value: "projId",
          label: "项目编号"
        },
        {
          value: "projDescription",
          label: "项目描述"
        },
        {
          label: "审计机构",
          value: "dept"
        },
        {
          label: "被审计机构",
          value: "std"
        },
        {
          label: "立项时间",
          value: "createDate"
        }
      ],
      formDynamic: [],
      formDynamicConfig: {},
      model: "",
      modelConfig: {}
    };
  },
  methods: {
    handleAdd() {
      if (this.formDynamicConfig.hasOwnProperty(this.modelConfig.value)) {
        this.$Message.error("请勿添加重复字段");
        return;
      }
      this.formDynamic.push(this.modelConfig);
      // this.formDynamicConfig[this.modelConfig.value] = "";
      this.$set(this.formDynamicConfig, this.modelConfig.value, "");
    },
    handleRemove(item, index) {
      this.formDynamic.splice(index, 1);
      delete this.formDynamicConfig[item.value];
    },

    selectChange(val) {
      this.modelConfig = val;
    }
  },
  components: {}
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.fades-enter-active,
.fades-leave-active {
  transition: opacity 0.5s;
}
.fades-enter,
.fades-leave-to {
  opacity: 0;
}
.fades-leave,
.fades-enter-to {
  opacity: 1;
}
</style>

本例子有一丢丢缺陷,当不勾选select时点击add item会报错。但是问题不大,可做非空判断。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!