1. Effect display

The main interface:

Add books:

Modify interface:

Two, front-end implementation

1. Vue. CLI establishment project

Command line input Vue UI (VUE version 3.0 or later)

vue ui

Manually create the project select the following configuration to use:Waiting for the completion of project creation, because I also need to write back end, I open it with IDEA (IDEA needs to download vue.js extension)Can be entered in terminal

npm run serve

Run the official initial project and the project is created

Vue +elementUI quickly build front-end pages

Install elementUI

Go to the elementUI website element.eleme.cn/#/zh-CN/com… NPM is recommended for installation, which works better with the WebPack packaging tool.

npm i element-ui -S

Write the following in main.js:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  el: '#app'.render: h= > h(App)
});
Copy the code

Check the package.json file in the directory. If the elementUI version number is already there, the installation is successful

2. Use elementUI

Go to elementUI’s official websiteElement. The eleme. Cn / # / useful – cn/com…Find the corresponding component code and select it as needed. For this project, the official sample in the layout container is selected and then modifiedTo change static pages to dynamic pages with vue, the main code is as follows:

  <el-container style="height: 700px; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu router :default-openeds="[' 0 ', '1']">
        <el-submenu v-for="(item,index) in $router.options.routes" :index="index+''">
          <template slot="title"><i class="el-icon-setting"></i>{{ item.name }} </template>
          <el-menu-item v-for="item2 in item.children" :index="item2.path"
                                      :class="$route.path==item2.path? 'is-active':''"   v-if="item2.show">{{item2.name}}</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>
    <el-container>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
Copy the code

In <el-menu Router: default-Openeds =”[‘0′,’1’]>, the router attribute maps to the index attribute of its subcomponent. : default-Openeds is enabled by default and is based on the index attribute.

Router /index.js:

const routes = [
  {
    path:'/'.name:'Library Management'.component:Index,
    redirect:'/BookManage'.children:[
      {
        path:'/BookManage'.name:'Book Search'.show:true.component:BookManage
      },
      {
        path:'/AddBook'.name:'Add book'.show:true.component:AddBook
      },
      {
        path:'/update'.show:false.component: BookUpdate
      }
    ]
  },
]
Copy the code

Bookmanage.vue:

 <el-table
      :data="tableData"
      border
      style="width: 100%">
    <el-table-column
        fixed
        prop="id"
        label="Number"
        width="150">
    </el-table-column>
    <el-table-column
        prop="name"
        label="Title"
        width="600">
    </el-table-column>
    <el-table-column
        prop="author"
        label="The author"
        width="350">
    </el-table-column>
    <el-table-column
        fixed="right"
        label="Operation"
        width="200">
      <template slot-scope="scope">
        <el-button @click="handleClick(scope.row)" type="text" size="small">Modify the</el-button>
        <el-button @click="deleteBook(scope.row)" type="text" size="small">delete</el-button>
      </template>
    </el-table-column>
  </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        page-size="10"
        :total="this.total"
        @current-change="page">
    </el-pagination>
Copy the code

Page-size =”10″ pagination :total=”this. Total “pagination =”this

Addbook.vue:

<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="Book Name" prop="name">
      <el-input v-model="ruleForm.name" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="The author" prop="author">
      <el-input v-model="ruleForm.author" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">add</el-button>
      <el-button @click="resetForm('ruleForm')">reset</el-button>
    </el-form-item>
  </el-form>
Copy the code

Modify the book interface bookupdate. vue:

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

    <el-form-item label="Book Number" prop="name">
      <el-input v-model="ruleForm.id" readonly style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="Book Name" prop="name">
      <el-input v-model="ruleForm.name" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="The author" prop="author">
      <el-input v-model="ruleForm.author" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">Modify the</el-button>
      <el-button @click="resetForm('ruleForm')">reset</el-button>
    </el-form-item>
  </el-form>
Copy the code

(3) Front-end test

The front-end page is not a dynamic page from the beginning. When there is no back-end data interface, fake data and static page can be tested in the front end first. After building the page, we wait for the implementation of the back-end interface, and then dynamically set up the page with Ajax to obtain back-end data.

Second, back-end implementation

1. Quickly create a Spring Boot project using Spring Initializr in IDEA

Choose the above dependencies. Lombok has a lot of convenient annotations, such as @data and so on. DevTools implements hot deployment. This project uses JPA to link MySQL.

2. Write a configuration file

Change the port because the default port for front-end service is also 8080

3. Prepare your database

4. Write entity classes

@Entity
@Data
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String author;
}
Copy the code

Where ID is set to the primary key and is set to increment.

5, the Dao layer

public interface BookRepository extends JpaRepository<Book.Integer> {}Copy the code

This interface only needs to inherit from the JpaRepository interface. JpaRepository encapsulates basic data operation methods, including basic add, delete, change, search, paging, sorting, etc.

6, test,

@SpringBootTest
class BookRepositoryTest {

    @Autowired
    private BookRepository bookRepository;

    @Test
    void findAll(a){
        System.out.println(bookRepository.findAll());
    }

    @Test
    void save(a){
        Book book =new Book();
        book.setName("springboot");
        book.setAuthor("Zhang");
        Book book1=bookRepository.save(book);
        System.out.println(book1);
    }

    @Test
     void findById(a){
        Book book=bookRepository.findById(1).get();
        System.out.println(book);
     }

     @Test
     void update(a){
        Book book=new Book();
        book.setId(18);
        book.setName("Test");
        Book book1=bookRepository.save(book);
         System.out.println(book1);
     }

     @Test
     void delete(a){
        bookRepository.deleteById(18); }}Copy the code

Test cruD functions separately and make sure they are available before completing the interface.

7. Write controllers

The simplification omits the Service layer

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Book> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
        Pageable pageable= PageRequest.of(page-1,size);
        return bookRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody Book book){
        Book result=bookRepository.save(book);
        if(result! =null) {return "success";
        }else {
            return "error"; }}@GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result=bookRepository.save(book);
        if(result! =null) {return "success";
        }else {
            return "error"; }}@DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){ bookRepository.deleteById(id); }}Copy the code

The IMPLEMENTATION of CRUD function conforms to RESTful style

8. Solve cross-domain problems

Because front-end 8080’s access to back-end 8181 constitutes a cross-domain problem, the back-end solves the cross-domain problem by writing configuration classes as follows:

@Configuration
public class CrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ * *")
                .allowedOrigins("*")
                .allowedMethods("GET"."HEAD"."POST"."PUT"."DELETE"."OPTIONS")
                                .allowCredentials(false)
                                .maxAge(3600)
                                .allowedHeaders("*"); }}Copy the code

3. Front-end and back-end data connectivity

1. Install AXIOS on the front end

First add axios with the following command:

vue add axios

The project directory is too many

2. Connect the front end to the back end interface

Fetching back-end database data, and paging operations:

    page(currentPage){
      this.$axios.get('http://localhost:8181/book/findAll/'+currentPage+'/ 10').then(resp= > {
        this.tableData = resp.data.content;
        this.total=resp.data.totalElements
      })
    }
  },
  created(){
    this.$axios.get('http://localhost:8181/book/findAll/1/10').then(resp= > {
      this.tableData = resp.data.content;
      this.total=resp.data.totalElements
    })
  },
Copy the code

Delete operation:

    deleteBook(row){
      this.$axios.delete('http://localhost:8181/book/deleteById/'+row.id).then(resp= > {
        this.$message('Deleted successfully! ');
        window.location.reload(); })}Copy the code

Add operation:

 submitForm(formName) {
        this.$refs[formName].validate((valid) = > {
          if (valid) {
            this.$axios.post('http://localhost:8181/book/save'.this.ruleForm).then(resp= > {
                 if(resp.data =='success') {this.$message('Added successfully! ');
                   this.$router.push('/BookManage')}}}else {
            return false; }}); }Copy the code

Modify operation:

submitForm(formName) {
      this.$refs[formName].validate((valid) = > {
        if (valid) {
          this.$axios.put('http://localhost:8181/book/update'.this.ruleForm).then(resp= > {
            if(resp.data =='success') {this.$message('Modified successfully! ');
              this.$router.push('/BookManage')}}}else {
          return false; }}); }Copy the code

The above is part of the code

** Detailed code **

Gitee.com/chenyjoe/vu gitee 】 【…

Making 】 【 github.com/chenyjoe/Vu…