springboot+vue实现增删查改小demo

源码下载地址
后台

前端

技术栈

前端

开发工具:WebStorm
开发框架:vue + axios
包管理工具: npm
打包工具:webpack

后端
开发工具:IDEA
开发框架:Springboot + mybatis
打包工具:maven
数据库: MySQL

前后端目录

后端目录
在这里插入图片描述
前端目录
在这里插入图片描述

部分代码

page1.vue

<template>
 <div>
     <el-button type="primary" class="b1" icon="el-icon-plus" @click="add()">添加</el-button>
     <el-dialog
             id="dialog"
             :append-to-body="true"
             title="添加图书"
             :visible.sync="centerDialogVisible"
             width="50%"
             center>


         <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

             <el-form-item label="编号" prop="isbn">
                 <el-input :disabled="dis" v-model="ruleForm.isbn"></el-input>
             </el-form-item>

             <el-form-item label="书名" prop="bookName">
                 <el-input v-model="ruleForm.bookName"></el-input>
             </el-form-item>

             <el-form-item label="作者" prop="author">
                 <el-input v-model="ruleForm.author"></el-input>
             </el-form-item>
         </el-form>
         <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save(flag,'ruleForm')">确 定</el-button>
     </span>
     </el-dialog>

     <el-form :inline="true" :model="formInline" class="demo-form-inline">
         <el-form-item label="搜索">
             <el-input v-model="formInline.user" placeholder="搜索"></el-input>
         </el-form-item>
         <el-form-item label="搜索方式">
             <el-select v-model="formInline.region" placeholder="书名">
                 <el-option label="书名" value="name"></el-option>
                 <el-option label="作者" value="author"></el-option>
             </el-select>
         </el-form-item>
         <el-form-item>
             <el-button type="primary" @click="onSubmit">搜索</el-button>
         </el-form-item>
     </el-form>

    <el-table
            :data="tableData"
            style="width: 100%">
        <el-table-column
                label="编号"
                width="180">
            <!--  使用slot-scope   获取 tableData值      -->
            <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.isbn }}</span>
            </template>
        </el-table-column>
        <el-table-column
                label="书名"
                width="180">
            <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.bookName }}</span>

            </template>
        </el-table-column>
        <el-table-column
                label="作者"
                width="180">
           <!--            -->
            <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.author }}</span>

            </template>
        </el-table-column>
        <el-table-column label="操作">
            <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>
    <div id="page1">
        <el-pagination
                background
                layout="prev, pager, next"
                page-size="4"
                @current-change="currentPage"
                :total="total">
        </el-pagination>
    </div>
 </div>
</template>
<style>
    .el-input{
        width: 35%;
    }
    .b1{
        float: left;
    }
    #page1{
        float: left;
        margin-top: 20px;
    }
</style>
<script>
    export default {
        created(){
            const _this = this;
            axios.defaults.withCredentials = true;

            this.getData(1)
            // //请求后端数据
            // axios.get('http://localhost:8081/books/1/4').then(resp => {
            //     _this.tableData = resp.data.list;
            //     console.log(resp.data.list)
            // })
        },
        data() {
            return {   //双向绑定
                flag:null,
                dis:null,
                pageSize:null,
                total:null,
                tableData: {
                    isbn:'',
                    bookName:'',
                    author:'',
                },
                formInline: {
                    user: '',
                    region: ''
                },
                centerDialogVisible: false,
                ruleForm: {
                    isbn:'',
                    bookName:'',
                    author:'',
                },
                //校验规则
                rules: {
                    isbn: [
                        { required: true, message: '请输入编号', trigger: 'blur' },
                    ],
                    bookName: [
                        { required: true, message: '请输入书名', trigger: 'blur' },
                    ],
                    author: [
                        { required: true, message: '请输入作者', trigger: 'change' }
                    ]

                }
            }
        },
        methods: {
            add(){
                this.centerDialogVisible = true;
                this.flag = 1;
                this.dis = false
                this.ruleForm.isbn = null;
                this.ruleForm.author = null
                this.ruleForm.bookName = null
            },


            save(flag,ruleForm){
                if(flag == 1) {
                    //this 操作
                    const _this = this;
                    //数据校验
                    this.$refs[ruleForm].validate((valid) => {
                            if (valid) {
                                this.centerDialogVisible = false;
                                //直接传递对象
                                //function (resp){} 中的this 指的是 function这个方法

                                //resp => {} 中的this 指的是 vue的this
                                axios.post('http://localhost:8081/book/add', this.ruleForm).then(function (resp) {
                                    if (resp.data == 'success') {
                                        _this.$message({
                                            message: '图书添加成功!',
                                            type: 'success'
                                        })
                                    } else {
                                        _this.$message({
                                            message: '图书添加失败!!!',
                                            type: 'error'
                                        })
                                    }
                                }),
                                _this.getData(1);
                            } else {
                                this.centerDialogVisible = true;
                                return false;
                            }
                        }
                    );
                }
                else if(flag == 0){
                    //this 操作
                    const _this = this;

                    this.dis = true    //修改图书信息时,禁用编号输入
                    //数据校验
                    this.$refs[ruleForm].validate((valid) =>{
                            if(valid){
                                this.centerDialogVisible = false;
                                console.log(this.ruleForm.author + this.ruleForm.bookName)
                                //直接传递对象
                                axios.post('http://localhost:8081/book/updateBook',this.ruleForm).then(function (resp) {
                                    if(resp.data == 'success'){
                                        _this.$message({
                                            message: '图书修改成功!',
                                            type: 'success'
                                        })
                                    }else{
                                        _this.$message({
                                            message: '图书修改失败!!!',
                                            type: 'error'
                                        })
                                    }
                                })
                            }else {
                                this.centerDialogVisible = true;
                                return false;
                            }
                        }
                    );
                }
            },
            currentPage(currentPage){
               this.getData(currentPage)
            },
            getData(currentPage){
                const _this = this;
                console.log(currentPage)
                //请求后端数据
                axios.get('http://localhost:8081/books/'+currentPage+'/4').then(function (resp) {
                    _this.tableData = resp.data.list
                    _this.total = resp.data.total

                })
            },
            handleEdit(index, row){
                this.centerDialogVisible = true
                this.flag = 0;
                this.ruleForm.isbn = row.isbn;
                this.ruleForm.author = row.author
                this.ruleForm.bookName = row.bookName
                this.dis = true
            },
            handleDelete(index, row) {

                this.$confirm('是否删除该图书记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    axios.post('http://localhost:8081/book/deleteBook/' + row.isbn).then(resp => {
                            if (resp.data == 'success') {
                                this.$message({
                                    message: '图书删除成功!',
                                    type: 'success'
                                }),
                                this.getData(1);
                            } else {
                                this.$message({
                                    message: '图书删除成功!!!',
                                    type: 'error'
                                })
                            }
                        })



                }).catch(() => {

                });
                //直接传递对象

            }, onSubmit() {
                const _this = this
                const sel = this.formInline.region
                const user = this.formInline.user
                if(sel == 'name'){
                    axios.get('http://localhost:8081/book/name/'+user).then(function (resp) {
                        _this.tableData = resp.data.list
                        _this.total = resp.data.total
                    })
                }else if(sel == 'author'){
                    axios.get('http://localhost:8081/book/author/'+user).then(function (resp) {
                        _this.tableData = resp.data.list
                        _this.total = resp.data.total
                    })
                }
            }


        }
    }
</script>

application.yml


spring:
  datasource:
    url:  jdbc:mysql://localhost:3306/act5?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root

pagehelper:
    helperDialect: mysql
  # 分页合理化参数,默认值为false。
  # 当该参数设置为 true 时,pageNum<=0 时会查询第一页,
  # pageNum>pages(超过总数时),会查询最后一页
    reasonable: true
  # 支持通过 Mapper 接口参数来传递分页参数
    support-methods-arguments: true

mybatis:
  config-location: classpath:mybatis-config.xml
server:
  port: 8081

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--   开启驼峰命名 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 引入 pageHelper插件 -->
    <!--注意这里要写成PageInterceptor, 5.0之前的版本都是写PageHelper, 5.0之后要换成PageInterceptor-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--reasonable:分页合理化参数,默认值为false,直接根据参数进行查询。
              当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。-->
            <!--<property name="reasonable" value="true"/>-->
        </plugin>
    </plugins>
</configuration>

controller

package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.BookMapper;
import com.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class BookController {

    @Autowired
    BookMapper bookMapper;

	//分页
    @RequestMapping("/books/{page}/{size}")
    public PageInfo<Book> findBooks(@PathVariable String page, @PathVariable String size){
        //当前页总数
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(size));
        List<Book> books = bookMapper.findBooks();
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return pageInfo;
    }

    @PostMapping("/book/add")
    public String addBook(@RequestBody Book book){
        try {
            bookMapper.addBook(book);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

    @PostMapping("/book/updateBook")
    public String updateBook(@RequestBody Book book){
        try {
            bookMapper.updateBook(book);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

    @GetMapping("/book/name/{bookName}")
    public PageInfo<Book> findBookByBookName( @PathVariable String bookName){
        List<Book> list = bookMapper.findBookByBookName(bookName);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @GetMapping("/book/author/{author}")
    public PageInfo<Book> findBookByAuthor( @PathVariable String author){
        List<Book> list = bookMapper.findBookByAuthor(author);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @PostMapping("/book/deleteBook/{isbn}")
    public String deleteBook( @PathVariable String isbn){
        try {
            System.out.println(isbn);
            int i = bookMapper.deleteBook(isbn);
            System.out.println(i);
            return "success";
        }catch (Exception e){
            return "error";
        }
    }

}

跨域配置

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrosConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>