在父组件中点击弹出模态框

171 阅读1分钟
在弹出模态框时需要将数据渲染上去,使用克隆

deepClone.js

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

使用:

    <el-dialog
      :title="preTitle+'标签'"    //模态框标题不同
      :visible="visible"
      @close="close"
      class="dialog"
      v-draggable      //可以拖拽模态框
    >
        //...
    </el-dialog>

导入 import { deepClone } from 'deepClone.js'

  watch: {
    visible: {
      handler (visible) {
        if (visible) {
          if (this.type === 'edit') {   //编辑状态下需要克隆数据,新增时不需要
            this.ruleForm = deepClone(this.sourceData);
          } else {
            // this.ruleForm = this.$options.data().ruleForm;
            this.$refs.ruleForm?.resetFields();
          }
        } 
      },
    },
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    type: String,
    sourceData: Object,
  },
  computed: {
    preTitle() {
      switch(this.type) {
        case 'add': return '新增';    //新增标签
        case 'edit': return '编辑';   //编辑标签
      }
      return '';
    }
  },

父组件中

<el-button @click="showAddDialog('add')" type="primary" size="mini" icon="el-icon-plus">新增</el-button>
<el-button type="primary" size="small" @click="showAddDialog('edit',scope.row)">编辑</el-button>
<AddDialog :visible.sync="addDialog.show" :type="addDialog.type" :sourceData="addDialog.sourceData" @refresh="getList"/>
//导入AddDialog模态框
 components:{
    AddDialog
  },
data(){
    return{
      addDialog: { // 对话框
        show: false,
        type: '',
        sourceData: {}
      },
    }
},
methods:{
    showAddDialog(type,data){
      this.addDialog.sourceData = data
      this.addDialog.type = type
      this.addDialog.show = true
    },
}