SPA项目开发之CRUD+表单验证

本文介绍如何使用Element-UI的Form组件进行表单验证,以及实现新增、修改、删除功能的方法。详细解释了表单验证规则的设定、表单提交时的校验流程,并展示了如何在Vue中结合Element-UI实现CRUD操作,包括搜索、编辑和删除功能的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、表单验证

element-UI的Form组件提供了表单验证的功能,只需要通过rules属性传入约定的验证规则,并将Form-Item的prop属性设置为需校验的字段名即可,重点代码如下图标注部分:

接着可在提交时判断校验能否通过:

注:有多个表单时,怎么在提交进行区分?

我们在rules这里写了对表单的验证规则,但是我们如何在methods里进行指定的表单进行认证,所以我们一开始就在el-form里写了ref="ruleForm",我们在methods里就可以用

表单校验效果:

2、新增/修改/删除的实现

这些功能的实现比较简单,需要注意的是修改跟删除时的传值问题,可在<template>上使用特殊的slot-scope特性,即可接收传递给插槽的prop:

完整代码:

<template>
  <div style="padding: 20px;">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索:">
        <el-input size="small" v-model="title" placeholder="文章标题"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <!-- 列表的第一列为序号,为保护数据信息,防止恶意爬虫,不能把后端给的id直接显示,应该显示行号 -->
      <el-table-column type="index" :index="indexMethod" label="序号" min-width="1">
      </el-table-column>
      <el-table-column sortable prop="title" label="文章内容" min-width="3">
      </el-table-column>
      <el-table-column sortable prop="body" label="文章内容" min-width="6">
      </el-table-column>
      <el-table-column label="操作" min-width="2">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination style="margin-top: 20px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="currentPage" :page-sizes="[5,10, 20, 30, 50]" :page-size="100" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 新增修改弹出框 -->
    <el-dialog :title="articleTitle" :visible="articleDialogFormVisible" @close="doCancel">
      <el-form :model="articleForm" :rules="articleRules" ref="articleForm">
        <el-form-item label="文章标题" :label-width="articleFormLabelWidth" prop="title">
          <el-input v-model="articleForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="articleFormLabelWidth" prop="body">
          <el-input type="textarea" v-model="articleForm.body" rows="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doCancel">取 消</el-button>
        <el-button type="primary" @click="doSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Articles',
    data: function() {
      return {
        articleRules: { //定义表单校验规则
          title: [{
              required: true,
              message: '请输入文章标题',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '文章标题长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          body: [{
            required: true,
            message: '请输入文章内容',
            trigger: 'change'
          }]
        },
        title: null,
        listData: [],
        currentPage: 1,
        rows: 5,
        total: 0,
        articleTitle: null,
        articleDialogFormVisible: false, //dialog弹出框默认隐藏
        articleFormLabelWidth: '120px',
        articleForm: {
          id: null,
          title: null,
          body: null
        }
      };
    },
    methods: {
      search: function() {
        var url = this.axios.urls.ARTICLE_LIST;
        var formData = {
          title: this.title,
          pageNumber: this.currentPage,
          pageSize: this.rows
        }

        // 我们发现封装后的axios不需要再用qs.stringify(formData);做处理了
        this.axios.post(url, formData).then(response => {
          // 将后台返回的列表数据进行绑定
          this.listData = response.data.data.list
          // 将后台返回的总记录数进行绑定
          this.total = response.data.data.total;
        }).catch(function(error) {
          console.log(error);
        });
      },
      handleAdd() {
        this.articleTitle = '新增文章';
        this.articleDialogFormVisible = true; //打开dialog弹出框
      },
      handleEdit: function(index, row) {
        this.articleTitle = '编辑文章';
        this.articleForm.id = row.id;
        this.articleForm.title = row.title;
        this.articleForm.body = row.body;
        this.articleDialogFormVisible = true;
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //点击确定按钮的操作
          let url = this.axios.urls.ARTICLE_DEL;
          this.axios.post(url, {
            id: row.id
          }).then(response => {
            if (response.data.code = 200) {
              this.search();
              this.$message({
                message: response.data.msg,
                type: 'success'
              });
            } else {
              this.$message({
                message: response.data.msg,
                type: 'warning'
              });
            }
          });
        });
      },
      doCancel() {
        this.articleDialogFormVisible = false;
        this.doClearForm();
      },
      doClearForm: function() {
        this.articleForm.id = null;
        this.articleForm.title = null;
        this.articleForm.body = null;
        this.$refs['articleForm'].resetFields(); //清空表单验证信息
      },
      doSubmit() {
        this.$refs['articleForm'].validate((valid) => {
          if (valid) {//表单校验通过
            let url = this.axios.urls.ARTICLE_ADD_OR_EDIT;
            this.axios.post(url, this.articleForm).then(response => {
              if (response.data.code = 200) {
                this.articleDialogFormVisible = false;
                this.doClearForm();
                this.search();
                this.$message({
                  message: response.data.msg,
                  type: 'success'
                });
              } else {
                this.$message({
                  message: response.data.msg,
                  type: 'warning'
                });
              }
            });
          } else {//表单校验不通过
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleSizeChange: function(rows) {
        console.log("每页显示的记录数发生改变时会触发");
        this.currentPage = 1;
        this.rows = rows;
        this.search();
      },
      handleCurrentChange: function(page) {
        console.log("页码数发生改变时会触发");
        this.currentPage = page;
        this.search();
      },
      indexMethod(index) {
        return index + 1;
      }
    },
    created: function() {
      this.search();
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值