当前位置:   article > 正文

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

vue3前后端数据交互

一、前后端分离

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

 

         pom配置阿里云仓库

  1. <repositories>
  2. <repository>
  3. <id>nexus-aliyun</id>
  4. <name>nexus-aliyun</name>
  5. <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  6. <releases>
  7. <enabled>true</enabled>
  8. </releases>
  9. <snapshots>
  10. <enabled>false</enabled>
  11. </snapshots>
  12. </repository>
  13. <pluginRepositories>
  14. <pluginRepository>
  15. <id>public</id>
  16. <name>aliyun nexus</name>
  17. <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  18. <releases>
  19. <enabled>true</enabled>
  20. </releases>
  21. <snapshots>
  22. <enabled>false</enabled>
  23. </snapshots>
  24. </pluginRepository>
  25. </pluginRepositories>
  26. </repositories>

application.yml

  1. server:
  2. port: 9090
  3. spring:
  4. datasource:
  5. url: jdbc://mysql//localhost:3306/springboot-vue3
  6. driver-class-name: com.mysql.jdbc.Driver
  7. username: root
  8. password: root

         启动成功

        创建数据库表t_user

  1. CREATE TABLE `user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名',
  4. `date` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '日期',
  5. `address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地址',
  6. PRIMARY KEY (`id`)
  7. ) 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语句打印:        

  1. logging:
  2. level:
  3. com.example.springboot.mapper: debug

        Mybatis开启下划线自动转驼峰

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

        统一包装类Result

  1. /**
  2. * Controller统一返回的包装类
  3. */
  4. public class Result {
  5. private static final String SUCCESS_CODE = "200";
  6. private static final String ERROR_CODE = "500";
  7. private String code; // 返回的状态码。告诉前端这次请求成功还是失败
  8. private String msg; // 错误信息
  9. private Object data; // 包装的数据
  10. public Result(String code, String msg, Object data) {
  11. this.code = code;
  12. this.msg = msg;
  13. this.data = data;
  14. }
  15. public Result(String code, String msg) {
  16. this.code = code;
  17. this.msg = msg;
  18. }
  19. public Result() {
  20. }
  21. public String getCode() {
  22. return code;
  23. }
  24. public void setCode(String code) {
  25. this.code = code;
  26. }
  27. public String getMsg() {
  28. return msg;
  29. }
  30. public void setMsg(String msg) {
  31. this.msg = msg;
  32. }
  33. public Object getData() {
  34. return data;
  35. }
  36. public void setData(Object data) {
  37. this.data = data;
  38. }
  39. public static Result success(Object data) {
  40. return new Result(SUCCESS_CODE, "", data);
  41. }
  42. public static Result success() {
  43. return new Result(SUCCESS_CODE, "");
  44. }
  45. public static Result error(String msg) {
  46. return new Result(SUCCESS_CODE, msg);
  47. }
  48. }

二、Vue配置

        安装axios 1.4.0:

npm i axios

        配置环境变量

        .env.dev

  1. VITE_ENV = dev
  2. VITE_BASE_URL = 'http://localhost:9090'

        utils/request.js

  1. import axios from "axios";
  2. const request = axios.create({
  3. baseURL: 'http://localhost:9091',
  4. timeout: 30000
  5. })
  6. request.interceptors.request.use(config => {
  7. config.headers['Content-Type'] = 'application/json;charset=utf-8';
  8. return config
  9. }, error => {
  10. console.log('request error:' + error)//for error debug
  11. return Promise.reject(error)
  12. })
  13. request.interceptors.response.use(response =>{
  14. let res = response.data
  15. // res.code
  16. return res
  17. },error => {
  18. console.log('response error:' +error)
  19. return Promise.reject(error)
  20. })
  21. export default request

                导入request对象

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

         因为没有返回request的config

         跨域错误

         在后端修改配置即可

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

        2.在全局配置跨域

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.cors.CorsConfiguration;
  4. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  5. import org.springframework.web.filter.CorsFilter;
  6. @Configuration
  7. public class CrossOriginConfig {
  8. // 当前跨域请求最大有效时长。这里默认1
  9. private static final long MAX_AGE = 24 * 60 * 60;
  10. @Bean
  11. public CorsFilter corsFilter() {
  12. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  13. CorsConfiguration corsConfiguration = new CorsConfiguration();
  14. corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
  15. corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
  16. corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
  17. corsConfiguration.setMaxAge(MAX_AGE);
  18. source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
  19. return new CorsFilter(source);
  20. }
  21. }

查询数据:

  1. <el-button type="primary" @click="load" style="margin-left: 5px">查询数据</el-button>
  2. const state = reactive({
  3. tableData: [],
  4. form:{}
  5. })
  6. //请求后台数据 load去加载表格里
  7. const load = () =>{
  8. request.get('/user/selectAll?name='+name.value).then(res =>{
  9. //res.data就是后台返回的数组
  10. state.tableData = res.data
  11. })
  12. }
  13. load();

重置数据:

  1. <el-button type="info" @click="reset">重置数据</el-button>
  2. const reset = () =>{
  3. name.value = '';
  4. load();
  5. }

User

  1. package com.example.springboot.entity;
  2. /**
  3. * author: zx
  4. * time: 2023-06-25
  5. */
  6. public class User {
  7. private Integer id;
  8. private String name;
  9. private String date;
  10. private String address;
  11. private String userNo;
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getDate() {
  25. return date;
  26. }
  27. public void setDate(String date) {
  28. this.date = date;
  29. }
  30. public String getAddress() {
  31. return address;
  32. }
  33. public void setAddress(String address) {
  34. this.address = address;
  35. }
  36. public String getUserNo() {
  37. return userNo;
  38. }
  39. public void setUserNo(String userNo) {
  40. this.userNo = userNo;
  41. }
  42. }

UserController

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @Resource
  5. private UserMapper userMapper;
  6. @GetMapping("/selectAll")
  7. //user/selectAll?name=xxx
  8. public Result selectAll(@RequestParam String name){
  9. List<User> userList = userMapper.selectAll(name);
  10. return Result.success(userList);
  11. }
  12. }

UserMapper

  1. @Mapper
  2. public interface UserMapper {
  3. @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},'%') ")
  4. List<User> selectAll(String name);
  5. }

分页查询

国际化

  1. import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
  2. app.use(ElementPlus, {
  3. locale: zhCn,
  4. })

UserController

  1. //分页查询
  2. @GetMapping("/selectPage")
  3. //user/selectAll?name=xxx
  4. public Result selectPage(@RequestParam String name, @RequestParam Integer start, @RequestParam Integer pageSize){
  5. List<User> userList = userMapper.selectPage(name,start,pageSize);
  6. Integer total = userMapper.selectTotal(name);
  7. Map<String,Object> map = new HashMap<>();
  8. map.put("list",userList);
  9. map.put("total",total);
  10. return Result.success(map);
  11. }

UserMapper

  1. @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} ")
  2. List<User> selectPage(@Param("name") String name, @Param("start") Integer start, @Param("pageSize") Integer pageSize);
  3. @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},'%')")
  4. Integer selectTotal(@Param("name") String name);
  1. <div style="margin: 10px">
  2. <el-pagination background layout=" prev, pager, next,total,sizes"
  3. v-model:current-page="pageNum"
  4. v-model:page-size="pageSize"
  5. :page-sizes="[1, 2,5]"
  6. @size-change="load"
  7. @current-change="load"
  8. :total="total"/>
  9. </div>
  10. const total = ref(0)
  11. const pageNum = ref(1)
  12. const pageSize = ref(1)
  13. //请求后台数据 load去加载表格里
  14. const load = () => {
  15. //pageNum => start
  16. let start = (pageNum.value - 1) * pageSize.value
  17. request.get('/user/selectPage?name=' + name.value + '&start=' + start + '&pageSize=' + pageSize.value).then(res => {
  18. //res.data就是后台返回的数组
  19. state.tableData = res.data.list
  20. total.value = res.data.total
  21. })
  22. }
  23. load();

新增数据

UserController

  1. @PostMapping("save")
  2. public Result save(@RequestBody User user){
  3. userMapper.save(user);
  4. return Result.success();
  5. }

UserMapper

  1. @Insert("insert into t_user(name,date,address,user_no) values(#{name},#{date},#{address},#{userNo})")
  2. void save(User user);
  1. <el-button type="primary" @click="handleAdd">新增数据</el-button>
  2. <!--弹窗-->
  3. <el-dialog v-model="dialogFormVisible" title="信息" width="40%">
  4. <el-form :model="state.form" label-width="100px" style="padding-right:30px ">
  5. <el-form-item label="日期">
  6. <el-date-picker v-model="state.form.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width:100%"/>
  7. </el-form-item>
  8. <el-form-item label="姓名">
  9. <el-input v-model="state.form.name" autocomplete="off"/>
  10. </el-form-item>
  11. <el-form-item label="地址">
  12. <el-input v-model="state.form.address" autocomplete="off"/>
  13. </el-form-item>
  14. <el-form-item label="编号">
  15. <el-input v-model="state.form.userNo" autocomplete="off"/>
  16. </el-form-item>
  17. </el-form>
  18. <template #footer>
  19. <span class="dialog-footer">
  20. <el-button @click="dialogFormVisible = false">取消</el-button>
  21. <el-button type="primary" @click="save">确认</el-button>
  22. </span>
  23. </template>
  24. </el-dialog>
  25. import {ElMessage} from "element-plus";
  26. //新增数据 设置新的空的绑值对象 打开弹窗
  27. const handleAdd = () => {
  28. state.form = {}
  29. //打开弹窗
  30. dialogFormVisible.value = true
  31. }
  32. //保存数据,把数据插入到tableData中,并刷新页面,弹窗关闭
  33. const save = () => {
  34. request.post('/user/save', state.form).then(res => {
  35. if (res.code === '200') {
  36. ElMessage.success('操作成功')
  37. dialogFormVisible.value = false
  38. } else {
  39. ElMessage.error(res.msg)
  40. }
  41. })
  42. }

编辑数据

UserController

  1. @PutMapping("/update")
  2. public Result update(@RequestBody User user){
  3. userMapper.update(user);
  4. return Result.success();
  5. }

UserMapper

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

删除数据

UserController

  1. @DeleteMapping("/delete")
  2. public Result delete(@RequestParam Integer id){
  3. userMapper.delete(id);
  4. return Result.success();
  5. }

UserMapper

  1. @Delete("delete from t_user where id = #{id}")
  2. void delete(Integer id);
  1. <el-button link type="danger" size="default" @click.prevent="remove(scope.row.id)">删除</el-button>
  2. //删除数据 从index位置开始,删除一行即可
  3. const remove = (id) => {
  4. request.delete('/user/delete?id=' + id).then(res => {
  5. if (res.code === '200') {
  6. ElMessage.success('操作成功')
  7. //调用查询方法,更新表格数据
  8. load()
  9. dialogFormVisible.value = false
  10. } else {
  11. ElMessage.error(res.msg)
  12. }
  13. })
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/280009?site
推荐阅读
相关标签
  

闽ICP备14008679号