el-form的常用场景总结

88 阅读1分钟

用于搜索栏

写后台时经常要写搜索条件,而且很多页面都要这个功能,不如二次封装一下

image.png

// vue2 代码片段
<template>
  <el-form :inline="true" :model="ruleForm" :rules="rules" ref="myForm">
    <el-form-item prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('myForm')">搜索</el-button>
      <el-button type="primary" @click="clearForm">清空</el-button>
      <el-button @click="resetForm('myForm')">重置</el-button>
      <slot></slot>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        name: "",
      },
      rules: {},
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit("confirm", this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    clearForm() {
      Object.keys(this.ruleForm).forEach((item) => {
        this.ruleForm[item] = "";
      });
    },
  },
};
</script>
<style scoped>
.el-form-item {
  /* 这里默认有个22px margin-bottom,去掉它 */
  margin-bottom: 0;
}
</style>

这样除了基本的获取数据的功能外,加入slot来占位, 如果想加别的功能的话,可以直接在父组件上操作,这样就完成了基本的地次封装,以后再写这里就可以复用了

在对话框中应用form

这也是一种非常高频的应用场景了, 我在工作中经常会遇到的问题如下:

  • 关闭对话框后,再打开对话框时, 之前输入的数据还在, 这个问题的原因是, 对话框虽然关闭了, 但对话框内的组件没有销毁的原因, 我看了我们同事的解决方案, 就是给对话框内的组件声明一个showType, 关闭对话框时再改变这个值来重新渲染这个组件, 来达到清空数据的目的,这样虽然可行 ,但当我重新看elementUI的文档时, 发现一个属性值destroy-on-close, 完美解决, 可能我那个同事没有仔细阅读官方文档, 我把源码贴上, 方便以后来抄, 哈哈哈
<el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      destroy-on-close
    >
      <div class="dialog-item">
        <my-form v-if="showType == 1" @confirm="confirm" />
      </div>
</el-dialog>
  • 说明一下为啥还是有一个showType, 这是为了在一个页面内共用一个el-dialog, 其实大家肯定也是这么用的, 但不幸的是, 我在改我前任的代码时, 发现竟然有多个el-dialog, 而且每个的变量命名是dialog1, dialog2... 这样, 我....

未完待续