vue3,elementPlus和自己封装,点击 新增添加表单,删除表单,提交数据

ElementPlus下的form也有新增表单 如果你写H5等没找到合适的 自己也可以进行封装

实现3个代码讲解:1:ElementPlus的代码 2:自己书写的代码 3:自己把2的代码进行封装

1:ElementPlus的运行效果


在这里插入图片描述

点击提交

在这里插入图片描述

1:ElementPlus的代码



  <template>
  <el-form
    ref="formRef"
    :model="dynamicValidateForm"
    label-width="120px"
    class="demo-dynamic"
  >
    <el-form-item
      prop="email"
      label="Email"
      :rules="[
        {
          required: true,
          message: 'Please input email address',
          trigger: 'blur',
        },
        {
          type: 'email',
          message: 'Please input correct email address',
          trigger: ['blur', 'change'],
        },
      ]"
    >
      <el-input v-model="dynamicValidateForm.email" />
    </el-form-item>
    <el-form-item
      v-for="(domain, index) in dynamicValidateForm.domains"
      :key="domain.key"
      :label="'Domain' + index"
      :prop="'domains.' + index + '.value'"
      :rules="{
        required: true,
        message: 'domain can not be null',
        trigger: 'blur',
      }"
    >
      <el-input v-model="domain.value" />
      <el-button class="mt-2" @click.prevent="removeDomain(domain)"
        >Delete</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      <el-button @click="addDomain">新增</el-button>
      <el-button @click="resetForm(formRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";

const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{
  domains: DomainItem[];
  email: string;
}>({
  domains: [
    {
      key: 1,
      value: "",
    },
  ],
  email: "",
});

interface DomainItem {
  key: number;
  value: string;
}

const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
  }
};

const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: "",
  });
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
      console.log(dynamicValidateForm, "dynamicValidateForm");
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>  

2:自己书写的代码

在这里插入图片描述
点击提交的打印效果
在这里插入图片描述

 <template>
  <div class="box">
    <template v-for="(item, index) in dataForm" :key="item.id">
      <div
        class="box-b bg-ff"
        style="display: flex; justify-content: space-between"
      >
        <div>
          <div style="display: flex">
            <div class="">区域位置</div>
            <input v-model="item.ipchange" type="text" />
          </div>
          <div style="display: flex; margin-top: 10px">
            <div class="">危险有害因素</div>
            <input type="text" v-model="item.errorText" />
          </div>
        </div>
        <div>
          <el-button type="primary" @click="deleteClick(item.id)"
            >删除</el-button
          >
        </div>
      </div>
    </template>

    <div>
      <el-button type="primary" @click="handlerClick">新增</el-button>
      <el-button type="primary" @click="subMitClick">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
const dataForm = reactive([
  { id: 1, ipchange: "", errorText: "" },
  { id: 2, ipchange: "", errorText: "" },
]);
const handlerClick = () => {
  dataForm.push({ id: Date.now(), ipchange: "", errorText: "" });
};
const deleteClick = (id: number) => {
  dataForm.forEach((item, index) => {
    item.id == id ? dataForm.splice(index, 1) : "";
  });
};
const subMitClick = () => {
  console.log(dataForm, "dataForm");
};
</script>

<style scoped>
.bg-ff {
  background: #fff;
}
.box {
  width: 30vw;
  margin: auto;

  background: #fff;
}
.box-b {
  padding: 10px;
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  border-radius: 10px;
  border: 1px solid #000;
  margin-top: 10px;
}
</style>
 

2的代码量太多 我们都会进行封装

3:自己把2的代码进行封装

components/insertForm.vue

<template>
  <div>
    <template v-for="(item, index) in NewdataForm" :key="item.id">
      <div
        class="box-b bg-ff"
        style="display: flex; justify-content: space-between"
      >
        <div>
          <div style="display: flex">
            <div class="">区域位置</div>
            <input v-model="item.ipchange" type="text" />
          </div>
          <div style="display: flex; margin-top: 10px">
            <div class="">危险有害因素</div>
            <input type="text" v-model="item.errorText" />
          </div>
        </div>
        <div>
          <el-button type="primary" @click="deleteClick(item.id)"
            >删除</el-button
          >
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
const emit = defineEmits(["deleteClick"]);
const define = withDefaults(defineProps<{ dataForm: any[] }>(), {
  dataForm: () => [
    { id: 1, ipchange: "", errorText: "" },
    { id: 2, ipchange: "", errorText: "" },
  ],
});

//1: 这样不可以的; 下面的watch监听进行赋值的时候 NewdataForm=newvalue不可整体的赋值这个
// reactive  只能赋值到它下的某个属性下
//1: let errors = reactive( [...define.dataForm] );
// 2:但是使用这个 太麻烦
// 2:let NewdataForm = reactive({ dataForm: [...define.dataForm] });
// 3:使用 ref这个 可以直接赋值
let NewdataForm = ref([...define.dataForm]);

watch(define.dataForm, (newvalue) => {
  // errors=newvalue  //错误的写法 如上1:
  // NewdataForm.dataForm=newvalue;可以正常运行如上2:

  NewdataForm.value = newvalue;
});
const deleteClick = (id: number) => {
  emit("deleteClick", id);
};
defineExpose({ NewdataForm });
</script>

<style scoped>
</style>

主文件引入

  <template>
  <div class="box">
    <div>
      <insertForm
        ref="insertFormRef"
        :dataForm="dataForm"
        @deleteClick="deletenewClick"
      ></insertForm>
      <el-button type="primary" @click="handlerClick">新增</el-button>
      <el-button type="primary" @click="subMitClick">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import insertForm from "@/components/insertForm/index.vue";

import { ref, reactive } from "vue";
const insertFormRef = ref<InstanceType<typeof insertForm>>();
var dataForm = ref([
  { id: 1, ipchange: "", errorText: "" },
  { id: 2, ipchange: "", errorText: "" },
]);
const handlerClick = () => {
  dataForm.value.push({ id: Date.now(), ipchange: "", errorText: "" });
};
const deletenewClick = (id: number) => {
  dataForm.value.forEach((item, index) => {
    item.id == id ? dataForm.value.splice(index, 1) : "";
  });
};
const subMitClick = () => {
  dataForm.value = insertFormRef.value.NewdataForm;
  console.log(dataForm.value, "dataForm");
};
</script>

<style >
.bg-ff {
  background: #fff;
}
.box {
  width: 30vw;
  margin: auto;

  background: #fff;
}
.box-b {
  padding: 10px;
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  border-radius: 10px;
  border: 1px solid #000;
  margin-top: 10px;
}
</style>
 



 

效果一样
在这里插入图片描述

在这里插入图片描述
*

大多数人的疑问 我新增的input的vmodel绑定的值 和之前的表单一样的 ,都是ipchange: “”, errorText: “” 就是这样的 发给后端后端自己判断即可

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以尝试以下步骤来封装一个Vue 3和TypeScript下使用Element Plus的提交组件: 1. 安装必要的依赖: - Vue 3:`npm install vue@next` - TypeScript:`npm install -D typescript` - Element Plus:`npm install element-plus` 2. 创建一个新的Vue组件,并为其选择一个合适的名称,例如`FormSubmit.vue`。 3. 在`FormSubmit.vue`文件中,导入必要的模块和样式: ```vue <template> <!-- 内容 --> </template> <script lang="ts"> import { defineComponent } from 'vue'; import { ElButton, ElForm, ElFormItem } from 'element-plus'; export default defineComponent({ components: { ElButton, ElForm, ElFormItem, }, }); </script> <style scoped> /* Element Plus 样式 */ @import 'element-plus/packages/theme-chalk/src/index.scss'; /* 自定义样式 */ /* ... */ </style> ``` 4. 在模板中编写内容,并使用Element Plus的组件来构建: ```vue <template> <el-form ref="form" :model="formData" label-width="120px"> <el-form-item label="姓名" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> <!-- 更多项 --> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </template> <script lang="ts"> // ... export default defineComponent({ // ... data() { return { formData: { name: '', // 更多字段 } }; }, methods: { submitForm() { // 提交逻辑 if (this.$refs.form.validate()) { // 验证通过,执行提交操作 // ... } } } }); </script> ``` 这样,你就可以使用封装好的提交组件来方便地处理提交了。你可以根据实际需求添加更多的项,并在`submitForm`方法中实现你的提交逻辑。希望这可以帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值