说明:这篇文章是适用于已经学过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博客https://blog.csdn.net/qq_69183322/article/details/135747832
1.1后端配置:
1.1.1application.yml:
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_demo
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 1234
server:
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:
import axios from "axios";
const baseURL = '/api';
const instance = axios.create({baseURL})
instance.interceptors.response.use(
result=>{
return result.data;
},
err=>{
alert('服务错误');
return Promise.reject(err);
}
)
export default instance;
1.2.3api/user.js:
注意:api里的js文件名和文件内容,要根据实际的接口文档写,这里先写了一个打印功能的接口,方便教学
import request from '@/utils/request.js'
export const userHelloService = ()=>{
return request.get('/user/hello')
}
1.2.4router/index.js:
注意:别忘记在views文件夹下创建Login.vue和Layout.vue(本次教学没用到)
import { createRouter,createWebHistory } from "vue-router";
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'
//定义路由关系
const routes = [
{ path:'/login',component:LoginVue},
{ path:'/',component:LayoutVue}
]
//创建路由器
const router = createRouter({
history: createWebHistory(),
routes: routes
})
export default router
1.2.5main.js:
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App);
app.use(router)
app.use(ElementPlus)
app.mount('#app')
1.2.6vite.config.js:
注意:target里的url要根据后端的端口号进行修改
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server:{
proxy:{
'/api':{
target:'http://localhost:8080',
changeOrigin:true,
rewrite:(path)=>path.replace(/^\/api/,'')
}
}
}
})
二、从打印一个字符串开始
2.1 后端:
2.1.1 Controller:
启动该SpringBoot项目后,通过Get方式访问locahost:8080/user/hello,就会返回"Hello World! 2024 year"字符串
package com.example.test_demo.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/hello")
public String hello(){
return "Hello World! 2024 year";
}
}
2.2前端:
2.2.1api/user.js:
import request from '@/utils/request.js'
export const userHelloService = ()=>{
return request.get('/user/hello')
}
2.2.2App.vue:
为了方便演示,我直接在App.vue(Vue.js 项目的入口文件)中输出后端传递的字符串
<script setup>
import {ref} from 'vue'
import { userHelloService } from './api/user.js';
const variable1 = ref('')
const hello = async()=>{
let result = await userHelloService();
variable1.value = result
}
function clear(){
variable1.value = ''
}
</script>
<template>
<el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
<el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
<h1>输出:{{variable1}}</h1>
</template>
<style scoped>
</style>
2.3 实现效果:
点击Hello按钮时,打印后端返回的字符串"Hello World! 2024 year"
三、实现登录功能(多个参数的传递)
想要实现登录功能,那么在页面输入的username(用户名)和password(密码)信息要传递到后端,这样后端才能调用数据库进行验证该用户信息是否存在
3.1后端:
3.1.1 Controller:
package com.example.test_demo.Controller;
import com.example.test_demo.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/hello")
public String hello(){
return "Hello World! 2024 year";
}
@PostMapping("/login")
public String login(String username,String password){
System.out.println("用户名:"+username);
System.out.println("密码:"+password);
return "用户名:"+username+"\n密码:"+password;
}
}
3.2前端:
3.2.1api/user.js:
import request from '@/utils/request.js'
export const userHelloService = ()=>{
return request.get('/user/hello')
}
export const userLoginService = (loginData)=>{
const params = new URLSearchParams();
for(let key in loginData){
params.append(key,loginData[key])
}
return request.post('/user/login',params)
}
3.2.2App.vue:
<script setup>
import {ref} from 'vue'
import { userHelloService, userLoginService } from './api/user.js';
const variable1 = ref('')
const hello = async()=>{
let result = await userHelloService();
variable1.value = result
}
function clear(){
variable1.value = ''
}
const loginData = ref({
username: '',
password: ''
})
const login = async()=>{
let result = await userLoginService(loginData.value);
alert(result)
}
</script>
<template>
<el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
<el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
<h1>输出:{{variable1}}</h1>
<el-input v-model="loginData.username" placeholder="Please username" />
<el-input v-model="loginData.password" placeholder="Please password" />
<el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
<h1>username:{{loginData.username}}</h1>
<h1>password:{{loginData.password}}</h1>
</template>
<style scoped>
.el-input{
width: 200px;
display: flex;
justify-items: flex-start;
}
</style>
3.3 实现效果:
在页面输入用户名和密码后点击登录按钮,弹出登录用户信息后点击确认
后端显示:
可以看到后端接收到页面输入的登录信息了
四、单个参数传递
我们常常需要获取单个参数进行查询或者校验,例如,我们想通过获取id来查询信息,或者获取某一类的名字来查询该类的内容,这时候就需要传递单个参数信息了
4.1后端:
4.1.1 Controller:
package com.example.test_demo.Controller;
import com.example.test_demo.pojo.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/hello")
public String hello(){
return "Hello World! 2024 year";
}
@PostMapping("/login")
public String login(String username,String password){
System.out.println("用户名:"+username);
System.out.println("密码:"+password);
return "用户名:"+username+"\n密码:"+password;
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("获取删除的id="+id);
return "删除 id="+id+"的用户信息";
}
}
4.2 前端:
4.2.1api/user.js:
import request from '@/utils/request.js'
export const userHelloService = ()=>{
return request.get('/user/hello')
}
export const userLoginService = (loginData)=>{
const params = new URLSearchParams();
for(let key in loginData){
params.append(key,loginData[key])
}
return request.post('/user/login',params)
}
export const userDeletService = (id)=>{
return request.delete('user/'+id)
}
4.2.2App.vue:
<script setup>
import {ref} from 'vue'
import { userDeletService, userHelloService, userLoginService } from './api/user.js';
const variable1 = ref('')
const hello = async()=>{
let result = await userHelloService();
variable1.value = result
}
function clear(){
variable1.value = ''
}
const loginData = ref({
username: '',
password: ''
})
const login = async()=>{
let result = await userLoginService(loginData.value);
}
const id = ref()
const deleteById = async()=>{
let result = await userDeletService(id.value);
id.value = result
}
</script>
<template>
<el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
<el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
<h1>输出:{{variable1}}</h1>
<el-input v-model="loginData.username" placeholder="Please username" />
<el-input v-model="loginData.password" placeholder="Please password" />
<el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
<h1>username:{{loginData.username}}</h1>
<h1>password:{{loginData.password}}</h1>
输入删除的ID:<el-input v-model="id" placeholder="Please deleteId" />
<el-button type="danger" @click="deleteById" style="margin-top:10px">删除</el-button>
<h1>deleteById:{{id}}</h1>
</template>
<style scoped>
.el-input{
width: 200px;
display: flex;
justify-items: flex-start;
}
</style>