当前位置:   article > 正文

SpringBoot3 + Vue3 由浅入深的交互 基础交互教学_springboot3 vue3

springboot3 vue3

说明:这篇文章是适用于已经学过SpringBoot3和Vue3理论知识,但不会具体如何实操的过程的朋友,那么我将手把手从教大家从后端与前端交互的过程教学。

目录

一、创建一个SpringBoot3项目的和Vue3项目并进行配置

1.1后端配置:

1.1.1application.yml:

1.2前端配置:

1.2.1安装相应的依赖:

1.2.2utils/request.js:

1.2.3api/user.js:

1.2.4router/index.js:

1.2.5main.js:

1.2.6vite.config.js:

二、从打印一个字符串开始

2.1 后端:

2.1.1 Controller:

2.2前端:

2.2.1api/user.js:

2.2.2App.vue:

2.3 实现效果:

三、实现登录功能(多个参数的传递)

3.1后端:

3.1.1 Controller:

3.2前端:

3.2.1api/user.js:

3.2.2App.vue:

3.3 实现效果:

四、单个参数传递

4.1后端:

4.1.1 Controller:

4.2 前端:

4.2.1api/user.js:

4.2.2App.vue:

4.3 实现效果:


一、创建一个SpringBoot3项目的和Vue3项目并进行配置

Vue创建的过程可以参考我之前写的文章

Vue 工程化项目创建快速入门这篇就够了-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_69183322/article/details/135747832

1.1后端配置:

1.1.1application.yml:

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

1.2前端配置:

要创建utils、api、router、views文件夹

1.2.1安装相应的依赖:

npm install axios
npm install element-plus --save
npm install vue-router@4

1.2.2utils/request.js:

  1. import axios from "axios";
  2. const baseURL = '/api';
  3. const instance = axios.create({baseURL})
  4. instance.interceptors.response.use(
  5. result=>{
  6. return result.data;
  7. },
  8. err=>{
  9. alert('服务错误');
  10. return Promise.reject(err);
  11. }
  12. )
  13. export default instance;

1.2.3api/user.js:

注意:api里的js文件名和文件内容,要根据实际的接口文档写,这里先写了一个打印功能的接口,方便教学

  1. import request from '@/utils/request.js'
  2. export const userHelloService = ()=>{
  3. return request.get('/user/hello')
  4. }

1.2.4router/index.js:

注意:别忘记在views文件夹下创建Login.vue和Layout.vue(本次教学没用到)

  1. import { createRouter,createWebHistory } from "vue-router";
  2. import LoginVue from '@/views/Login.vue'
  3. import LayoutVue from '@/views/Layout.vue'
  4. //定义路由关系
  5. const routes = [
  6. { path:'/login',component:LoginVue},
  7. { path:'/',component:LayoutVue}
  8. ]
  9. //创建路由器
  10. const router = createRouter({
  11. history: createWebHistory(),
  12. routes: routes
  13. })
  14. export default router

1.2.5main.js:

  1. import './assets/main.css'
  2. import { createApp } from 'vue'
  3. import App from './App.vue'
  4. import router from '@/router'
  5. import ElementPlus from 'element-plus'
  6. import 'element-plus/dist/index.css'
  7. const app = createApp(App);
  8. app.use(router)
  9. app.use(ElementPlus)
  10. app.mount('#app')

1.2.6vite.config.js:

注意:target里的url要根据后端的端口号进行修改

  1. import { fileURLToPath, URL } from 'node:url'
  2. import { defineConfig } from 'vite'
  3. import vue from '@vitejs/plugin-vue'
  4. // https://vitejs.dev/config/
  5. export default defineConfig({
  6. plugins: [
  7. vue(),
  8. ],
  9. resolve: {
  10. alias: {
  11. '@': fileURLToPath(new URL('./src', import.meta.url))
  12. }
  13. },
  14. server:{
  15. proxy:{
  16. '/api':{
  17. target:'http://localhost:8080',
  18. changeOrigin:true,
  19. rewrite:(path)=>path.replace(/^\/api/,'')
  20. }
  21. }
  22. }
  23. })

二、从打印一个字符串开始

2.1 后端:

2.1.1 Controller:

启动该SpringBoot项目后,通过Get方式访问locahost:8080/user/hello,就会返回"Hello World! 2024 year"字符串

  1. package com.example.test_demo.Controller;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("user")
  7. public class UserController {
  8. @GetMapping("/hello")
  9. public String hello(){
  10. return "Hello World! 2024 year";
  11. }
  12. }

2.2前端:

2.2.1api/user.js:

  1. import request from '@/utils/request.js'
  2. export const userHelloService = ()=>{
  3. return request.get('/user/hello')
  4. }

2.2.2App.vue:

为了方便演示,我直接在App.vue(Vue.js 项目的入口文件)中输出后端传递的字符串

  1. <script setup>
  2. import {ref} from 'vue'
  3. import { userHelloService } from './api/user.js';
  4. const variable1 = ref('')
  5. const hello = async()=>{
  6. let result = await userHelloService();
  7. variable1.value = result
  8. }
  9. function clear(){
  10. variable1.value = ''
  11. }
  12. </script>
  13. <template>
  14. <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
  15. <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
  16. <h1>输出:{{variable1}}</h1>
  17. </template>
  18. <style scoped>
  19. </style>

2.3 实现效果:

 

点击Hello按钮时,打印后端返回的字符串"Hello World! 2024 year"

三、实现登录功能(多个参数的传递)

想要实现登录功能,那么在页面输入的username(用户名)和password(密码)信息要传递到后端,这样后端才能调用数据库进行验证该用户信息是否存在

3.1后端:

3.1.1 Controller:

  1. package com.example.test_demo.Controller;
  2. import com.example.test_demo.pojo.User;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. @RequestMapping("user")
  9. public class UserController {
  10. @GetMapping("/hello")
  11. public String hello(){
  12. return "Hello World! 2024 year";
  13. }
  14. @PostMapping("/login")
  15. public String login(String username,String password){
  16. System.out.println("用户名:"+username);
  17. System.out.println("密码:"+password);
  18. return "用户名:"+username+"\n密码:"+password;
  19. }
  20. }

3.2前端:

3.2.1api/user.js:

  1. import request from '@/utils/request.js'
  2. export const userHelloService = ()=>{
  3. return request.get('/user/hello')
  4. }
  5. export const userLoginService = (loginData)=>{
  6. const params = new URLSearchParams();
  7. for(let key in loginData){
  8. params.append(key,loginData[key])
  9. }
  10. return request.post('/user/login',params)
  11. }

3.2.2App.vue:

  1. <script setup>
  2. import {ref} from 'vue'
  3. import { userHelloService, userLoginService } from './api/user.js';
  4. const variable1 = ref('')
  5. const hello = async()=>{
  6. let result = await userHelloService();
  7. variable1.value = result
  8. }
  9. function clear(){
  10. variable1.value = ''
  11. }
  12. const loginData = ref({
  13. username: '',
  14. password: ''
  15. })
  16. const login = async()=>{
  17. let result = await userLoginService(loginData.value);
  18. alert(result)
  19. }
  20. </script>
  21. <template>
  22. <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
  23. <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
  24. <h1>输出:{{variable1}}</h1>
  25. <el-input v-model="loginData.username" placeholder="Please username" />
  26. <el-input v-model="loginData.password" placeholder="Please password" />
  27. <el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
  28. <h1>username:{{loginData.username}}</h1>
  29. <h1>password:{{loginData.password}}</h1>
  30. </template>
  31. <style scoped>
  32. .el-input{
  33. width: 200px;
  34. display: flex;
  35. justify-items: flex-start;
  36. }
  37. </style>

3.3 实现效果:

在页面输入用户名和密码后点击登录按钮,弹出登录用户信息后点击确认

 后端显示:

 可以看到后端接收到页面输入的登录信息了

四、单个参数传递

我们常常需要获取单个参数进行查询或者校验,例如,我们想通过获取id来查询信息,或者获取某一类的名字来查询该类的内容,这时候就需要传递单个参数信息了

4.1后端:

4.1.1 Controller:

  1. package com.example.test_demo.Controller;
  2. import com.example.test_demo.pojo.User;
  3. import org.springframework.web.bind.annotation.*;
  4. @RestController
  5. @RequestMapping("user")
  6. public class UserController {
  7. @GetMapping("/hello")
  8. public String hello(){
  9. return "Hello World! 2024 year";
  10. }
  11. @PostMapping("/login")
  12. public String login(String username,String password){
  13. System.out.println("用户名:"+username);
  14. System.out.println("密码:"+password);
  15. return "用户名:"+username+"\n密码:"+password;
  16. }
  17. @DeleteMapping("/{id}")
  18. public String delete(@PathVariable Integer id){
  19. System.out.println("获取删除的id="+id);
  20. return "删除 id="+id+"的用户信息";
  21. }
  22. }

4.2 前端:

4.2.1api/user.js:

  1. import request from '@/utils/request.js'
  2. export const userHelloService = ()=>{
  3. return request.get('/user/hello')
  4. }
  5. export const userLoginService = (loginData)=>{
  6. const params = new URLSearchParams();
  7. for(let key in loginData){
  8. params.append(key,loginData[key])
  9. }
  10. return request.post('/user/login',params)
  11. }
  12. export const userDeletService = (id)=>{
  13. return request.delete('user/'+id)
  14. }

4.2.2App.vue:

  1. <script setup>
  2. import {ref} from 'vue'
  3. import { userDeletService, userHelloService, userLoginService } from './api/user.js';
  4. const variable1 = ref('')
  5. const hello = async()=>{
  6. let result = await userHelloService();
  7. variable1.value = result
  8. }
  9. function clear(){
  10. variable1.value = ''
  11. }
  12. const loginData = ref({
  13. username: '',
  14. password: ''
  15. })
  16. const login = async()=>{
  17. let result = await userLoginService(loginData.value);
  18. }
  19. const id = ref()
  20. const deleteById = async()=>{
  21. let result = await userDeletService(id.value);
  22. id.value = result
  23. }
  24. </script>
  25. <template>
  26. <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
  27. <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
  28. <h1>输出:{{variable1}}</h1>
  29. <el-input v-model="loginData.username" placeholder="Please username" />
  30. <el-input v-model="loginData.password" placeholder="Please password" />
  31. <el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
  32. <h1>username:{{loginData.username}}</h1>
  33. <h1>password:{{loginData.password}}</h1>
  34. 输入删除的ID:<el-input v-model="id" placeholder="Please deleteId" />
  35. <el-button type="danger" @click="deleteById" style="margin-top:10px">删除</el-button>
  36. <h1>deleteById:{{id}}</h1>
  37. </template>
  38. <style scoped>
  39. .el-input{
  40. width: 200px;
  41. display: flex;
  42. justify-items: flex-start;
  43. }
  44. </style>

4.3 实现效果:

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

闽ICP备14008679号