[Element-UI] CUD (add, delete, modify) and form form verification (source code attached)

Table of contents

1. Introduction

1 Introduction

2. Function

2. CUD

1. Add modifications

1.1. Add pop-up window

1.2. Define variables

1.3. Definition method

1.4. Complete code

2. Delete

2.1. Definition method

3. Form verification

1. Add rules

2. Define rules

3. Submit event

4. Complete front-end code


1. Introduction

1 Introduction

        Addition, deletion, and modification are three operations commonly used in computer programming and database management . Using addition, deletion, and modification operations can help us manage and maintain data in the system or database to ensure the accuracy, integrity, and consistency of the data . They are very common operations in programming and database management and help improve the flexibility and maintainability of the system .

What they do:

  1. Add : By adding operations, new data or functions can be added to the system or database. This is important for extending the capabilities and functionality of the system. For example, in a student performance management system, new student information can be added through the add operation.
  2. Delete : The delete operation removes unnecessary data or functionality from the system or database. This is important for cleaning and maintaining data consistency. For example, in an online mall database, delisted or expired products can be removed from the database through a delete operation.
  3. Modify (Update) : Modify operations can update or change existing data or functions in the system or database. This can help maintain data accuracy and completeness. For example, in an employee information management system, employees' salary information can be updated through modification operations.

2. Function

        Element UI is a desktop component library based on Vue.js. It provides a rich set of user interface components, including tables, forms, dialog boxes, etc., for quickly building modern web applications.

 The main functions of adding, deleting, and modifying operations in Element UI are as follows:

  1. Add : In Element UI, you can use form components and dialog components to add data. Form components allow us to collect user-entered data and add the data to a database or server through a submit action. Through the dialog component, we can display a pop-up window to collect user-entered data and then add the data to the system.
  2. Delete : In Element UI, you can use table components and dialog components to realize the data deletion function. Through the table component, we can display the existing data in the system and provide a delete button for the user to operate. When the user clicks the delete button, a dialog box can pop up to confirm the deletion operation, and the data will be deleted from the database or server after confirmation. .
  3. Modification (Update) : In Element UI, you can use form components and dialog components to implement data modification functions. Through the form component, we can display the existing data in the system and provide edit buttons for users to operate. When the user clicks the edit button, a dialog box can pop up to display the data editing interface, and the data will be updated to the database after the user submits the modification. or in the server.

        Addition, deletion and modification operations can help us manage and maintain data in Element UI. Whether adding new data, deleting old data, or modifying existing data, it can be quickly implemented through the components and functions provided by Element UI, and provides a friendly user interface and interactive experience. This helps speed development and improves system availability and ease of use .

2. CUD

1. Add modifications

Before this we need to write our back-end code so that we can perform subsequent operations

1.1. Add pop-up window

First, go to our component | Element's official website and find our pop-up component. I've provided that below as well.

<el-button type="primary" plain @click="dialogFormVisible = true">新增</el-button>
<!--    弹窗-->
    <el-dialog title="新增页面" :visible.sync="dialogFormVisible" @close="clear">
      <el-form :model="book">
        <el-form-item label="书籍名称" :label-width="formLabelWidth">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="书籍类型" :label-width="formLabelWidth">
          <el-select v-model="book.booktype" placeholder="请选择活动区域">
            <el-option v-for="t in types" :label="t.name" :value="t.name" :key="'key_'+t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>

1.2. Define variables

data() {
    return {
      // 是否打开弹窗
      dialogFormVisible: false,
      // 弹窗标题
      title: '新增页面',
      // 定义数组接收数据
      book:
        {id: '', bookname: '', price: '', booktype: ''}
      ,
      // 类型
      types: [],
      // 输入框长度
      formLabelWidth: '100px',

    }
  }

1.3. Definition method

 // 初始化方法
    clear() {
      this.dialogFormVisible = false;
      this.title = '新增页面';
      this.book = {
        id: '',
        bookname: '',
        price: '',
        booktype: ''
      }
    }
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;

      if (row) {
        this.title = '编辑页面';
        this.book.id = row.id;
        this.book.bookname = row.bookname;
        this.book.price = row.price;
        this.book.booktype = row.booktype;
      }

    }
    // 增加修改提交
    editSubmit() {

      //表单验证
      this.$refs['book'].validate((valid) => {
        if (valid) {
          //验证通过执行增加修改方法

          let params = {
            id: this.book.id,
            bookname: this.book.bookname,
            price: this.book.price,
            booktype: this.book.booktype
          }

          //获取后台请求书籍数据的地址
          let url = this.axios.urls.BOOK_ADD;

          if (this.title == "编辑页面") {//如果是点击的编辑页面更改访问路径
            url = this.axios.urls.BOOK_EDIT;
          }
          this.axios.post(url, params).then(r => {
            this.clear();//关闭窗口
            this.query({});//刷新
          }).catch(e => {

          });
        } else {
          // console.log('error submit!!');
          return false;
        }
      });

    }
  created() {
    this.types = [{id: 1, name: '玄幻'},
      {id: 2, name: '计算机'},
      {id: 3, name: '散文'},
      {id: 4, name: '古典'},
      {id: 5, name: '文学'},
      {id: 6, name: '教育'},
      {id: 7, name: '悬疑'},]
//初始化查询的方法
    this.query({})
  }

1.4. Complete code

<template>
  <div class="Book" style="padding: 30px;">
    <!-- 输入框搜索 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="书籍名称 : ">
        <el-input v-model="bookname" placeholder="书籍名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="onSubmit">查询</el-button>
        <el-button type="primary" plain @click="dialogFormVisible = true">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 书籍的书籍表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="书籍ID"></el-table-column>
      <el-table-column prop="bookname" label="书籍名称"></el-table-column>
      <el-table-column prop="price" label="书籍价格"></el-table-column>
      <el-table-column prop="booktype" label="书籍类型"></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit-outline" type="primary"
                     @click="handleEdit(scope.$index, scope.row)">编 辑
          </el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删
            除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="padding: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                     background :page-sizes="[10, 20, 30, 40]" :page-size="rows"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--    弹窗-->
    <el-dialog title="新增页面" :visible.sync="dialogFormVisible" @close="clear">
      <el-form :model="book">
        <el-form-item label="书籍名称" :label-width="formLabelWidth">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="书籍类型" :label-width="formLabelWidth">
          <el-select v-model="book.booktype" placeholder="请选择活动区域">
            <el-option v-for="t in types" :label="t.name" :value="t.name" :key="'key_'+t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data() {
    return {
      bookname: '',
      tableData: [],
      rows: 10,
      total: 0,
      page: 1,
      // 是否打开弹窗
      dialogFormVisible: false,
      // 弹窗标题
      title: '新增页面',
      // 定义数组接收数据
      book:
        {id: '', bookname: '', price: '', booktype: ''}
      ,
      // 类型
      types: [],
      // 输入框长度
      formLabelWidth: '100px',
    }
  },
  methods: {
    // 初始化方法
    clear() {
      this.dialogFormVisible = false;
      this.title = '新增页面';
      this.book = {
        id: '',
        bookname: '',
        price: '',
        booktype: ''
      }
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;

      if (row) {
        this.title = '编辑页面';
        this.book.id = row.id;
        this.book.bookname = row.bookname;
        this.book.price = row.price;
        this.book.booktype = row.booktype;
      }

    },
    // 增加修改提交
    editSubmit() {

      let params = {
        id: this.book.id,
        bookname: this.book.bookname,
        price: this.book.price,
        booktype: this.book.booktype
      }

      //获取后台请求书籍数据的地址
      let url = this.axios.urls.BOOK_ADD;

      if (this.title == "编辑页面") {//如果是点击的编辑页面更改访问路径
        url = this.axios.urls.BOOK_EDIT;
      }
      this.axios.post(url, params).then(r => {
        this.clear();//关闭窗口
        this.query({});//刷新
      }).catch(e => {

      });

    },
    handleSizeChange(r) {
      //当页大小发生变化
      let params = {
        bookname: this.bookname,
        rows: r,
        page: this.page
      }
      this.query(params);
    },
    handleCurrentChange(p) {
      //当前页码大小发生变化
      let params = {
        bookname: this.bookname,
        rows: this.rows,
        // 分页
        page: p
      }
      // console.log(params)
      this.query(params);
    },
    query(params) {
      //获取后台请求书籍数据的地址
      let url = this.axios.urls.BOOK_BOOKLIST;
      this.axios.get(url, {
        params: params
      }).then(d => {
        this.tableData = d.data.rows;
        this.total = d.data.total;
      }).catch(e => {

      });

    },
    onSubmit() {
      let params = {
        bookname: this.bookname
      }
      console.log(params)
      this.query(params);
      this.bookname = ''
    }
  },
//初始化调用
  created() {
    this.types = [{id: 1, name: '玄幻'},
      {id: 2, name: '计算机'},
      {id: 3, name: '散文'},
      {id: 4, name: '古典'},
      {id: 5, name: '文学'},
      {id: 6, name: '教育'},
      {id: 7, name: '悬疑'},]
    this.query({})
  }
}
</script>

<style>
</style>

2. Delete

2.1. Definition method

  
  // 删除
    handleDelete(index, row) {
      console.log(index, row)
      let url = this.axios.urls.BOOK_DEL;
      this.axios.post(url, {id: row.id}).then(d => {
        this.query({})
        this.$message({
          message: '恭喜你,删除成功',
          type: 'success'
        });
      }).catch(e => {
        this.$message('已取消');
      });
    }

3. Form verification

1. Add rules

You need to add :model="book" :rules="rules" ref="book" to the form in elementui . :model and ref must be the same.

      <el-form :model="book" :rules="rules" ref="book">

Add prop attributes inside <el-form-item>

2. Define rules

      //表单验证
      rules: {
        //定义验证格式
        bookname: [
          {required: true, message: '请输入书籍名称', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入书籍价格', trigger: 'change'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
        ],
        booktype: [
          {required: true, message: '请输入书籍类型', trigger: 'blur'}
        ]
      }

3. Submit event

Add it to the submitted event


 this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });

formName: the name in the form: model="book" or ref="book"

    // 增加修改提交
    editSubmit() {

      //表单验证
      this.$refs['book'].validate((valid) => {
        if (valid) {
          //验证通过执行增加修改方法

          let params = {
            id: this.book.id,
            bookname: this.book.bookname,
            price: this.book.price,
            booktype: this.book.booktype
          }

          //获取后台请求书籍数据的地址
          let url = this.axios.urls.BOOK_ADD;

          if (this.title == "编辑页面") {//如果是点击的编辑页面更改访问路径
            url = this.axios.urls.BOOK_EDIT;
          }
          this.axios.post(url, params).then(r => {
            this.clear();//关闭窗口
            this.query({});//刷新
          }).catch(e => {

          });
        } else {
          // console.log('error submit!!');
          return false;
        }
      });


    }

When your rules are required, execute your method of adding and modifying, or other methods.

4. Complete front-end code

<template>
  <div class="Book" style="padding: 30px;">
    <!-- 输入框搜索 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="书籍名称 : ">
        <el-input v-model="bookname" placeholder="书籍名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="onSubmit">查询</el-button>
        <el-button type="primary" plain @click="dialogFormVisible = true">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 书籍的书籍表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="书籍ID"></el-table-column>
      <el-table-column prop="bookname" label="书籍名称"></el-table-column>
      <el-table-column prop="price" label="书籍价格"></el-table-column>
      <el-table-column prop="booktype" label="书籍类型"></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit-outline" type="primary"
                     @click="handleEdit(scope.$index, scope.row)">编 辑
          </el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删
            除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="padding: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                     background :page-sizes="[10, 20, 30, 40]" :page-size="rows"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--    弹窗-->
    <el-dialog title="新增页面" :visible.sync="dialogFormVisible" @close="clear">
      <el-form :model="book" :rules="rules" ref="book">
        <el-form-item label="书籍名称" :label-width="formLabelWidth" prop="bookname">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="书籍类型" :label-width="formLabelWidth" prop="booktype">
          <el-select v-model="book.booktype" placeholder="请选择活动区域">
            <el-option v-for="t in types" :label="t.name" :value="t.name" :key="'key_'+t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data() {
    return {
      bookname: '',
      tableData: [],
      rows: 10,
      total: 0,
      page: 1,
      // 是否打开弹窗
      dialogFormVisible: false,
      // 弹窗标题
      title: '新增页面',
      // 定义数组接收数据
      book:
        {id: '', bookname: '', price: '', booktype: ''}
      ,
      // 类型
      types: [],
      // 输入框长度
      formLabelWidth: '100px',
      //表单验证
      rules: {
        //定义验证格式
        bookname: [
          {required: true, message: '请输入书籍名称', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入书籍价格', trigger: 'change'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
        ],
        booktype: [
          {required: true, message: '请输入书籍类型', trigger: 'blur'}
        ]
      },

    }
  },
  methods: {
    // 初始化方法
    clear() {
      this.dialogFormVisible = false;
      this.title = '新增页面';
      this.book = {
        id: '',
        bookname: '',
        price: '',
        booktype: ''
      }
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;

      if (row) {
        this.title = '编辑页面';
        this.book.id = row.id;
        this.book.bookname = row.bookname;
        this.book.price = row.price;
        this.book.booktype = row.booktype;
      }

    },
    // 删除
    handleDelete(index, row) {
      console.log(index, row)
      let url = this.axios.urls.BOOK_DEL;
      this.axios.post(url, {id: row.id}).then(d => {
        this.query({})
        this.$message({
          message: '恭喜你,删除成功',
          type: 'success'
        });
      }).catch(e => {
        this.$message('已取消');
      });
    },
    // 增加修改提交
    editSubmit() {

      //表单验证
      this.$refs['book'].validate((valid) => {
        if (valid) {
          //验证通过执行增加修改方法

          let params = {
            id: this.book.id,
            bookname: this.book.bookname,
            price: this.book.price,
            booktype: this.book.booktype
          }

          //获取后台请求书籍数据的地址
          let url = this.axios.urls.BOOK_ADD;

          if (this.title == "编辑页面") {//如果是点击的编辑页面更改访问路径
            url = this.axios.urls.BOOK_EDIT;
          }
          this.axios.post(url, params).then(r => {
            this.clear();//关闭窗口
            this.query({});//刷新
          }).catch(e => {

          });
        } else {
          // console.log('error submit!!');
          return false;
        }
      });


    },
    handleSizeChange(r) {
      //当页大小发生变化
      let params = {
        bookname: this.bookname,
        rows: r,
        page: this.page
      }
      this.query(params);
    },
    handleCurrentChange(p) {
      //当前页码大小发生变化
      let params = {
        bookname: this.bookname,
        rows: this.rows,
        // 分页
        page: p
      }
      // console.log(params)
      this.query(params);
    },
    query(params) {
      //获取后台请求书籍数据的地址
      let url = this.axios.urls.BOOK_BOOKLIST;
      this.axios.get(url, {
        params: params
      }).then(d => {
        this.tableData = d.data.rows;
        this.total = d.data.total;
      }).catch(e => {

      });

    },
    onSubmit() {
      let params = {
        bookname: this.bookname
      }
      console.log(params)
      this.query(params);
      this.bookname = ''
    }
  },
  created() {
    this.types = [{id: 1, name: '玄幻'},
      {id: 2, name: '计算机'},
      {id: 3, name: '散文'},
      {id: 4, name: '古典'},
      {id: 5, name: '文学'},
      {id: 6, name: '教育'},
      {id: 7, name: '悬疑'},]
    this.query({})
  }
}
</script>

<style>
</style>

That’s it for my sharing, thank you all for discussing in the comment area! ! !

Guess you like

Origin blog.csdn.net/weixin_74383330/article/details/133343463