vue3 + element plus 的表单校验

新增弹框的表单校验 直接上代码

新增功能基本是每个程序都需要的 下面这个直接可以拿去复用 v3是没有this的所以表单的校验和v2还是有区别的

	<el-dialog
      title="添加视图"
      :before-close="handleClose"
      v-model="data.Newlyincreased"
    >
      <el-form ref="ruleForm" :model="data.form" :rules="data.rules">
        <el-form-item label="视图名称:" label-width="100px" prop="viewName">
          <el-input v-model="data.form.viewName" autocomplete="off">el-input>
        el-form-item>
        <el-form-item label="视图类型:" label-width="100px" prop="viewType">
          <el-select
            v-model="data.form.viewType"
            style="width: 100%"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in data.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          el-select>
        el-form-item>
        <el-form-item label="是否有效:" prop="radio" label-width="100px">
          <el-radio-group v-model="data.form.radio">
            <el-radio :label="1">el-radio>
            <el-radio :label="0">el-radio>
          el-radio-group>
        el-form-item>
        <el-form-item label="描述:" prop="describe" label-width="100px">
          <el-input v-model="data.form.describe" :rows="2" type="textarea" />
        el-form-item>
      el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消el-button>
          <el-button type="primary" @click="confirm_xz()">确 定el-button>
        div>
      template>
    el-dialog>
import { reactive, ref } from "vue";
import { ElMessageBox } from "element-plus";
export default {
  setup() {
    const data = reactive({
      Newlyincreased: false,
      form: {
        viewName: "",
        viewType: "",
        describe: "",
        radio: 1,
      },
      rules: {
        viewName: [
          { required: true, message: "视图名称不能为空!", trigger: "blur" },
        ],
        viewType: [
          { required: true, message: "视图类型不能为空!", trigger: "change" },
        ],
        radio: [
          { required: true, message: "是否有效不能不选!", trigger: "change" },
        ],
        describe: [
          { required: true, message: "描述不能为空!", trigger: "blur" },
        ],
      },
    });
    const ruleForm = ref(null);
    const methods = {
      confirm_xz() {
        ruleForm.value.validate((valid) => {
          if (valid) {
            alert("aaa");
          } else {
            return false;
          }
        });
      },
      handleClose(done) {
        ElMessageBox.confirm("确认关闭?")
          .then((_) => {
            done();
            ruleForm.value.resetFields();
          })
          .catch((_) => {});
      },
    };
    return {
      ...methods,
      ruleForm,
      data,
    };
  },
};

你可能感兴趣的:(vue.js,javascript,前端)