Vue+springboot front-end separation interaction (quick start)

foreword

After learning the technology of SpringBoot, I think that the current development method of thymeleaf+SpringBoot is not used much, and most of them are using the development method of front-end and back-end separation , one of which is the development method of Vue+SpringBoot .
Separate development of front and back ends is a popular trend now, so I suggest that friends who want to build projects quickly must learn about the development method of vue+springboot.
idea, node.js mysql
Here we prepare with idea development tools according to the development habits of most people.
You need to install nodejs first. Of course, the students here must have learned vue, and node.js must have been installed. I won't go into too much detail here.
Install node.js
node.js official website: https://nodejs.org/zh-cn/

Specific code address: Baidu network disk download
link: https://pan.baidu.com/s/1fWO0i5iGxz2U8U4vmABIzA
Extraction code: wmlg

Install vue-cli scaffolding

Use the cmd command to open the command line, and enter the following command
to change the installation command for versions above vue3.0 to this : npm install -g @vue/cli
insert image description here

npm install -g @vue/cli@4。4.6

Here I personally suggest to directly install the 4.4.6 version of the scaffolding, because after watching a lot of videos, there are more or less incompatible things in other versions, and other versions have to be replaced later, so it is better to directly install the 4.4.6 version of the standard The glue is safe. Of course, this is just my personal suggestion, I hope it can save you from detours and hair loss haha~~

Start the vue project manager

After the installation is successful,
enter in the command line window: vue ui (note that in the location where you want to create the project, if you want to create a project on the d drive, switch to the d drive and enter this command.) The startup is successful
insert image description here
!
insert image description here

After the startup is successful, it will enter the Vue project manager.
insert image description here
The method of use has been written in my last blog: https://blog.csdn.net/lj20020302/article/details/129402966 .

Data interaction

Front-end and back-end data interaction requires axios to operate, so we need to download axios first.
Download the vue project and open the terminal: Enter the following command
insert image description here
After the installation is complete, add the following code on the page you need to request:

created() {
    
    
        const _this = this;
        axios.get('http://localhost:8082/list').then(function (resp) {
    
    
          _this.students =resp.data;
        })
  }

We initialize the function, write a callback function, and print data. This time you can print out the data in your own database.
For cross-domain problems, we create a new configuration class CrosConfig, you can refer to the following code:

package com.guo.config;

import org.springframework.context.annotation.Bean;
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 {
    
    
    @Bean
    public WebMvcConfigurer corsConfigurer() {
    
    
        return new WebMvcConfigurer() {
    
    
            @Override
            public void addCorsMappings(CorsRegistry registry) {
    
    
                registry.addMapping("/**")
                        .allowCredentials(false)
                        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                        .allowedOrigins("*");
            }
        };
    }

}

In this way, the simple data interaction between the front and back ends has been completed.

Use of Element-ui

Official website: https://element.eleme.cn/2.0/#/zh-CN/
Vue integrates Element UI
The main tags of Element UI:

  • el-container: Build the entire page frame
  • el-aside: Build the left menu
  • el-menu: left menu content, common attributes:
    • :default-openeds: The menu opened by default, linked by the index value of the menu.
    • :default-active: The menu selected by default, associated with the index value of the menu.
  • el-submenu: expandable menu, common attributes:

index: The subscript of the menu, text type, not numeric type.

  • template: The menu name corresponding to el-submenu.
  • i: Set the menu icon, set through the class attribute:
    • el-icon-message
    • el-icon-menu
    • el-icon-setting
  • el-menu-item: The sub-node of the menu, which cannot be expanded, common attributes: index: The subscript of the menu, text type, cannot be numeric type.
    There are many components in the official website, which can be played freely.
    insert image description here
    insert image description here

I am using a layout container, you can directly copy the code below to your own page.
insert image description here

Routing and dynamic navbar

When we develop, we need the effect of dynamically reading the page,
so we need to define an item on the label to get the index in the route, and display the dynamic effect through different index values, $route.path==item2.path ?'is-active': '' is when the path we visit is consistent with the path of the subpage in the router, 'is-active': is activated when this condition is true.
For example, when we visit localhost:8080/BookManage, and the path of the subpage in the router is also /BookManage, the condition is met and this attribute is selected.

 <el-submenu v-for="(item,index) in $router.options.routes" :index="index+''" v-if="item.show">
            <template slot="title">{
    
    {
    
    item.name}}</template>
            <el-menu-item v-for="(item2,index2) in item.children" :index="item2.path"
                          :class="$route.path==item2.path?'is-active':''">{
    
    {
    
    item2.name}}</el-menu-item>
          </el-submenu>

insert image description here
Implement click to switch pages:

  • Add the router attribute to the tag
  • Add a tag to the page, which is a container that dynamically renders the router you choose.
  • The index value of the label is the router to jump to.

:index="item2.path" Put the path of the page to jump to and it will be ok.
If you don’t add it, you can’t jump to your subpage, because when we load the page, we load the main page first. This tag opens a window for the loaded main page, so that it can load the window just like app.vue.

Paging query data

Use the Element UI label component
with pagination query
insert image description here
pagination code

<el-pagination
                background
                layout="prev, pager, next"
                :page-size="pageSize"
                :total="total"
                @current-change="page">
        </el-pagination>

@current-change Click Response
The overall page looks like this
insert image description here

We just need to add a PageRequest in the backend code

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

You can achieve the effect of pagination query.

adding data

Similarly, Element UI has written all these things for us, as long as we know how to use it, it is ok, so this Element UI can build a front-end web page very quickly.
insert image description here
Element UI form data verification
Define the rules object, and set the inspection rules for each option of the form in the rules object

rules: {
    
    
                    name: [
                        {
    
     required: true, message: '图书名称不能为空', trigger: 'blur' }
                    ],
                    author:[
                        {
    
     required: true, message: '作者不能为空', trigger: 'blur' }
                    ]
                }
  • required: true: whether it is a required item
  • message: 'The book name cannot be empty': prompt information
  • trigger: 'blur': trigger event, (lose focus)

The front-end form requires two-way binding

:model="ruleForm" :rules="rules"

The model is bound to data, and the rules are bound to inspection.
The front-end js code is as follows:

submitForm(formName) {
    
    
//与后端数据交互,把前端的数据传到后端,用post直接传一个对象this.ruleForm
                const _this = this
                this.$refs[formName].validate((valid) => {
    
    
                    if (valid) {
    
    
                        axios.post('http://localhost:8181/book/save',this.ruleForm).then(function(resp){
    
    
                            if(resp.data == 'success'){
    
    
                                _this.$alert('《'+_this.ruleForm.name+'》添加成功!', '消息', {
    
    
                                    confirmButtonText: '确定',
                                    callback: action => {
    
    
                                        _this.$router.push('/BookManage')//点击确定直接回调到/BookManage页面
                                    }
                                })
                            }
                        })
                    } else {
    
    
                        return false;
                    }
                });

The backend directly calls the save method of JPA

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

modify delete data

change the data

We first need to get the following id on the bookmanger page:

edit(row) {
    
    
                this.$router.push({
    
    
                    path: '/update',
                    query:{
    
    
                        id:row.id
                    }
                })
            },

Then go back to the update page,

methods: {
    
    
            submitForm(formName) {
    
    
                const _this = this
                this.$refs[formName].validate((valid) => {
    
    //这个valid 表示的是验证是否通过输出回是一个布尔类型的值
                    if (valid) {
    
    //如果为ture,则进行下面的请求
                        axios.put('http://localhost:8181/book/update',this.ruleForm).then(function(resp){
    
    
                            if(resp.data == 'success'){
    
    
                                _this.$alert('《'+_this.ruleForm.name+'》修改成功!', '消息', {
    
    
                                    confirmButtonText: '确定',
                                    callback: action => {
    
    
                                        _this.$router.push('/BookManage')
                                    }
                                })
                            }
                        })
                    } else {
    
    
                        return false;
                    }
                });
            },
            resetForm(formName) {
    
    
                this.$refs[formName].resetFields();//置为空
            }
        },
        created() {
    
    
            const _this = this
			//我们在路径里面给它拼接一下,把它的id给返回到我们的后端程序里。
            axios.get('http://localhost:8181/book/findById/'+this.$route.query.id).then(function(resp){
    
    
                _this.ruleForm = resp.data
            })
        }

The analysis of the method is in the comments in the code.

Backend controller request

 @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";
        }
    }

delete data

Deletion is often the simplest operation in CURD. You only need to call the delete method that comes with Jpa.
Backend request :

 @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
    
    
        bookRepository.deleteById(id);
    }

Add a click event to the delete button
insert image description here
and then implement the specific js code:

deleteBook(row){
    
    
                const _this = this
                axios.delete('http://localhost:8181/book/deleteById/'+row.id).then(function(resp){
    
    
                    _this.$alert('《'+row.name+'》删除成功!', '消息', {
    
    
                        confirmButtonText: '确定',
                        callback: action => {
    
    
                            window.location.reload()
                        }
                    })
                })
            }

Seeing this, it shows that the readers have a strong hands-on ability. The quick start operation of vue+springboot has almost been completed.
Come on, programmer

Guess you like

Origin blog.csdn.net/lj20020302/article/details/129506248