vue 新增和編輯用同一個表單,el-form表單提交後清空表單資料操作
阿新 • • 發佈:2020-08-04
在專案中做聯絡人的新增和編輯功能,點選父級頁面的新增和編輯按鈕,用的是同一個表單彈窗,資料新增和編輯用同一個彈窗,沒有在彈窗使用v-if,效能不是很好,彈窗中有表單,在編輯彈窗表單資料之後關閉彈窗,然後點選新增的時候,彈窗裡的表單資料還是之前編輯的資料,無法做到清空表單資料,接下來是解決方法了,嘿嘿
首先是不管是新增還是編輯,都需要將子元件需要的物件屬性一一寫出來,傳給子元件,
然後是主要用到了el-form表單有一個清空重置表單資料的事件方法resetField(),在子元件表單彈窗開啟的時候清空一下,在關閉子元件表單彈窗的時候還需要呼叫resetField()去重置表單資料。這樣編輯資料之後再次開啟新增資料,頁面不會有之前的資料存在,也不會出現驗證資訊在頁面上。
1. 在父級頁面呼叫子級彈框表單元件(AddEdit.vue)
<!-- form是子元件的form表單資料,meg是子元件彈窗的標題(新增或者編輯) --> <!-- <add-edit :msg.sync="msg" v-if='msg' :form='form'></add-edit> --> <!-- 沒有使用v-if 是因為頻繁點選編輯和新增的話,效能方面不是很好--> <template> <el-button @click='addClick'>新增</el-button> <el-button @click='editClick(scope.row)'>編輯</el-button> <!-- 子元件彈窗 --> <add-edit :msg.sync="msg" :form='formData'></add-edit> </template> <script> export default { data() { return { formData: {} } },methods: { addClick() { //需要將子元件需要的物件屬性傳過去,這一步必須得有,這樣在子元件才可以清空表單 this.formData = { name: '',email: '',phone: '' } this.msg = '新增' },editClick(row) { this.formData = row; this.msg = '編輯' } } } </script>
2. 點選父級頁面的編輯按鈕,將人員資訊傳遞給AddEdit.vue
<template> <el-dialog :visible.sync="isShow" width="500px" class="edit-contact" :before-close="closeDialog"> <span slot="title">{{msg}}聯絡人</span> <el-form :model="form" ref="ruleForm" label-width="100px" :rules="rules" size="small"> <el-form-item :label="it.label" :prop="it.prop" v-for="it in formLabel" :key="it.prop"> <el-input v-model="form[it.prop]" :placeholder="`請輸入${it.label}`"></el-input> </el-form-item> </el-form> <div class="base-btn-action"> <el-button size="small" type="primary" @click="saveContact">{{form.id?'編輯':'新增'}}</el-button> <el-button size="small" @click="closeDialog">取 消</el-button> </div> </el-dialog> </template>
<script> export default { props: { msg: { //“新增”或者“編輯” type: String,default: "" },form: { //接收父元件傳過來得物件資料 type: Object,default: () => {} } },data() { return { formLabel: [ { label: "姓名",prop: "name" },{ label: "郵箱",prop: "email" },{ label: "聯絡方式",prop: "phone" } ],rules: { name: [{ required: true,message: "請輸入姓名",trigger: "change" }],email: [ { required: true,message: "請輸入郵箱",trigger: "change" },{ type: "email",message: "請輸入正確的郵箱地址",trigger: ["blur"] } ],phone: [ { required: true,message: "請輸入手機號",trigger: "change" } ] } }; },computed: { //通過props的資料msg的值是否為空來判斷彈框顯示與否 isShow() { return this.msg === "" ? false : true; } },watch: { //監聽子元件彈窗是否開啟 msg(n) { //子元件開啟得情況 if (n !== '') { if (!this.$refs.ruleForm) { //初次開啟子元件彈窗的時候,form表單dom元素還沒載入成功,需要非同步獲取 this.$nextTick(() => { this.$refs.ruleForm.resetFields() // 去除驗證 }) } else { //再次開啟子元件彈窗,子元件彈窗的form表單dom元素已經載入好了,不需要非同步獲取 this.$refs.ruleForm.resetFields() // 去除驗證 } } },},methods: { closeDialog() { this.$emit("update:msg",""); setTimeout(() => { //關閉彈窗的時候表單也重置為初始值並移除校驗結果 this.$refs.ruleForm.resetFields(); },200); } } }; </script>
好了,問題解決了,在此記錄一下,以後可以翻回來再看看!
以上這篇vue 新增和編輯用同一個表單,el-form表單提交後清空表單資料操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。