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

一、前后端分离

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

 

         pom配置阿里云仓库

<repositories>

	<repository>
		<id>nexus-aliyun</id>
		<name>nexus-aliyun</name>
		<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
		<releases>
			<enabled>true</enabled>
		</releases>
		<snapshots>
			<enabled>false</enabled>
		</snapshots>
	</repository>
	
	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

</repositories>

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

         启动成功

        创建数据库表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的config

         跨域错误

         在后端修改配置即可

        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);
    }
}

查询数据:

<el-button type="primary" @click="load" style="margin-left: 5px">查询数据</el-button>



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



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

重置数据:

<el-button type="info" @click="reset">重置数据</el-button>



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<User> 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<User> 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<User> userList =  userMapper.selectPage(name,start,pageSize);
        Integer total = userMapper.selectTotal(name);
        Map<String,Object> 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<User> 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);
<div style="margin: 10px">
                <el-pagination background layout=" prev, pager, next,total,sizes"
                               v-model:current-page="pageNum"
                               v-model:page-size="pageSize"
                               :page-sizes="[1, 2,5]"
                               @size-change="load"
                               @current-change="load"
                               :total="total"/>
            </div>



 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);
<el-button type="primary" @click="handleAdd">新增数据</el-button>



<!--弹窗-->
        <el-dialog v-model="dialogFormVisible" title="信息" width="40%">
            <el-form :model="state.form" label-width="100px" style="padding-right:30px ">
                <el-form-item label="日期">
                    <el-date-picker v-model="state.form.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width:100%"/>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="state.form.name" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="state.form.address" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="编号">
                    <el-input v-model="state.form.userNo" autocomplete="off"/>
                </el-form-item>
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </span>
            </template>
        </el-dialog>


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);
 <el-button link type="danger" size="default" @click.prevent="remove(scope.row.id)">删除</el-button>



//删除数据 从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)
            }
        })
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值