Vue3学习(三)前后端数据交互

一、前后端分离

        IDEA软件、JDK1.8、Mysql5.7+、Navicat、SpringBoot2.x

Vue3学习(三)前后端数据交互_第1张图片

 Vue3学习(三)前后端数据交互_第2张图片

         pom配置阿里云仓库



	
		nexus-aliyun
		nexus-aliyun
		http://maven.aliyun.com/nexus/content/groups/public/
		
			true
		
		
			false
		
	
	
	
		
			public
			aliyun nexus
			http://maven.aliyun.com/nexus/content/groups/public/
			
				true
			
			
				false
			
		
	


application.yml

server:
  port: 9090

spring:
  datasource:
    url: jdbc://mysql//localhost:3306/springboot-vue3
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root

Vue3学习(三)前后端数据交互_第3张图片

         启动成功

        创建数据库表t_user

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名',
  `date` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '日期',
  `address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

        实现增删改查sql语句

        新增:

INSERT INTO `t_user`(name, date, address) VALUES('张三', '2023-06-25', '江苏省南京市');

        修改:

UPDATE t_user SET name = "李四" WHERE id = 1;

        删除:

DELETE FROM t_user WHERE id = 1;

        查询:

SELECT * FROM t_user WHERE name LIKE '%张%'

        分页查询:

SELECT * FROM t_user WHERE address LIKE '%南京%' LIMIT 0,2;

        SQL语句打印:        

logging:
  level:
    com.example.springboot.mapper: debug

        Mybatis开启下划线自动转驼峰

mybatis:
  configuration:
    map-underscore-to-camel-case: true  #  开启下划线自动转驼峰

        统一包装类Result

/**
 * Controller统一返回的包装类
 */
public class Result {
    private static final String SUCCESS_CODE = "200";
    private static final String ERROR_CODE = "500";

    private String code;   // 返回的状态码。告诉前端这次请求成功还是失败
    private String msg;    // 错误信息
    private Object data;   // 包装的数据

    public Result(String code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result() {
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static Result success(Object data) {
        return new Result(SUCCESS_CODE, "", data);
    }

    public static Result success() {
        return new Result(SUCCESS_CODE, "");
    }

    public static Result error(String msg) {
        return new Result(SUCCESS_CODE, msg);
    }
}

二、Vue配置

        安装axios 1.4.0:

npm i axios

        配置环境变量

        .env.dev

VITE_ENV = dev
VITE_BASE_URL = 'http://localhost:9090'

        utils/request.js

import axios from "axios";

const request = axios.create({
    baseURL: 'http://localhost:9091',
    timeout: 30000
})

request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    return config
}, error => {
    console.log('request error:' + error)//for error debug
    return Promise.reject(error)
})

request.interceptors.response.use(response =>{
    let res = response.data
    // res.code
    return res
},error => {
    console.log('response error:' +error)
    return Promise.reject(error)
    })

export default request

                导入request对象

import request from "../../utils/request";

         因为没有返回request的configVue3学习(三)前后端数据交互_第4张图片

         跨域错误

         在后端修改配置即可

        1.在controller加个注解@CrossOrigin解决

        2.在全局配置跨域

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CrossOriginConfig {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

查询数据:

查询数据



const state = reactive({
         tableData: [],
         form:{}
    })



//请求后台数据 load去加载表格里
    const load = () =>{
        request.get('/user/selectAll?name='+name.value).then(res =>{
            //res.data就是后台返回的数组
            state.tableData = res.data
            
        })
    }
    load();

重置数据:

重置数据



const reset = () =>{
        name.value = '';
        load();
    }

User

package com.example.springboot.entity;

/**
 * author: zx
 * time: 2023-06-25
 */
public class User {

    private Integer id;

    private String name;

    private String date;

    private String address;

    private String userNo;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUserNo() {
        return userNo;
    }

    public void setUserNo(String userNo) {
        this.userNo = userNo;
    }
}

UserController

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @GetMapping("/selectAll")
    //user/selectAll?name=xxx
    public Result selectAll(@RequestParam String name){
        List userList =  userMapper.selectAll(name);
        return Result.success(userList);
    }
}

UserMapper

@Mapper
public interface UserMapper {

    @Select("select * from t_user where name like concat('%',#{name},'%') or date like concat('%',#{name},'%') or address like concat('%',#{name},'%') or user_no like concat('%',#{name},'%')  ")
    List selectAll(String name);
}

分页查询

国际化

import zhCn from 'element-plus/dist/locale/zh-cn.mjs'


app.use(ElementPlus, {
    locale: zhCn,
})

UserController

//分页查询
    @GetMapping("/selectPage")
    //user/selectAll?name=xxx
    public Result selectPage(@RequestParam String name, @RequestParam Integer start, @RequestParam Integer pageSize){
        List userList =  userMapper.selectPage(name,start,pageSize);
        Integer total = userMapper.selectTotal(name);
        Map map = new HashMap<>();
        map.put("list",userList);
        map.put("total",total);
        return Result.success(map);
    }

UserMapper

@Select("select * from t_user where name like concat('%',#{name},'%') or date like concat('%',#{name},'%') or address like concat('%',#{name},'%') or user_no like concat('%',#{name},'%') order by id desc limit #{start},#{pageSize}  ")
    List selectPage(@Param("name") String name, @Param("start") Integer start, @Param("pageSize") Integer pageSize);

    @Select("select count(id) from t_user where name like concat('%',#{name},'%') or date like concat('%',#{name},'%') or address like concat('%',#{name},'%') or user_no like concat('%',#{name},'%')")
    Integer selectTotal(@Param("name") String name);
const total = ref(0) const pageNum = ref(1) const pageSize = ref(1) //请求后台数据 load去加载表格里 const load = () => { //pageNum => start let start = (pageNum.value - 1) * pageSize.value request.get('/user/selectPage?name=' + name.value + '&start=' + start + '&pageSize=' + pageSize.value).then(res => { //res.data就是后台返回的数组 state.tableData = res.data.list total.value = res.data.total }) } load();

新增数据

UserController

@PostMapping("save")
    public Result save(@RequestBody User user){
        userMapper.save(user);
        return Result.success();
    }

UserMapper

@Insert("insert into t_user(name,date,address,user_no) values(#{name},#{date},#{address},#{userNo})")
    void save(User user);
新增数据




        
            
                
                    
                
                
                    
                
                
                    
                
                
                    
                
            
            
        


import {ElMessage} from "element-plus";


//新增数据 设置新的空的绑值对象 打开弹窗
    const handleAdd = () => {
        state.form = {}
        //打开弹窗
        dialogFormVisible.value = true
    }




//保存数据,把数据插入到tableData中,并刷新页面,弹窗关闭
    const save = () => {
        request.post('/user/save', state.form).then(res => {
            if (res.code === '200') {
                ElMessage.success('操作成功')
                dialogFormVisible.value = false
            } else {
                ElMessage.error(res.msg)
            }
        })
    }

编辑数据

UserController

@PutMapping("/update")
    public Result update(@RequestBody User user){
        userMapper.update(user);
        return Result.success();
    }

UserMapper

 @Update("update t_user set name = #{name},date = #{date},address = #{address},user_no = #{userNo} where id = #{id}")
    void update(User user);
//保存数据,把数据插入到tableData中,并刷新页面,弹窗关闭
    const save = () => {
        request({
            url: state.form.id ? '/user/update' : '/user/save',
            method: state.form.id ? 'PUT' : 'POST',
            data: state.form
        }).then(res => {
            if (res.code === '200') {
                ElMessage.success('操作成功')
                //调用查询方法,更新表格数据
                load()
                dialogFormVisible.value = false
            } else {
                ElMessage.error(res.msg)
            }
        })
    }

删除数据

UserController

@DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id){
        userMapper.delete(id);
        return Result.success();
    }

UserMapper

    @Delete("delete from t_user where id = #{id}")
    void delete(Integer id);
 删除



//删除数据 从index位置开始,删除一行即可
    const remove = (id) => {
        request.delete('/user/delete?id=' + id).then(res => {
            if (res.code === '200') {
                ElMessage.success('操作成功')
                //调用查询方法,更新表格数据
                load()
                dialogFormVisible.value = false
            } else {
                ElMessage.error(res.msg)
            }
        })
    }

你可能感兴趣的:(学习)