vue 添加和編輯用同一個表單,el-form表單提交后清空表單數據操作
在項目中做聯系人的添加和編輯功能,點擊父級頁面的添加和編輯按鈕,用的是同一個表單彈窗,數據添加和編輯用同一個彈窗,沒有在彈窗使用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' :before-close='closeDialog'> <span slot='title'>{{msg}}聯系人</span> <el-form :model='form' ref='ruleForm' label- :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表單提交后清空表單數據操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。