之前本人在学习Vue3.x与Spring Boot整合时,遇到了诸如跨域、使用axios报错等问题,在成功解决后,总结了一些经验,于是将如何从零开始搭建Vue3.x+SpringBoot前后端分离项目写成文章,当分享和记录。示例使用的是Window系统。(默认已配置好Java环境、Maven、MySQL、npm以及下载并安装IDEA,因为本文目的是完成Vue3.x通过axios访问Spring Boot项目的接口)
yarn global add @vue/cli
# 或
npm install -g @vue/cli
安装完成后输入vue -V即可查看版本信息
vue ui
在浏览器输入http://localhost:8000/进入对应网页
接下来就是祈祷佛祖保佑创建过程不要报错了,如报错了也是请自行检索报错信息来解决。
vue add axios
打开axios.js文件,将倒数第二行的Vue.use(Plugin)注释掉
打开main.js文件,添加如下代码,注意添加的代码要在createApp(App).use(store).use(router).mount(’#app’)前面
import axios from 'axios'
import VueAxios from 'vue-cli-plugin-axios'
createApp(App).use(VueAxios, axios)
这样,Vue中的配置就完成了
Spring Boot项目中配置(如果你是在Vue项目中解决跨域问题,这部分可以不看)
Spring Boot中接口的编写就不展示了,因为这个并不是这篇文章的重点,跨域问题只需要在项目中编写一个配置类即可解决,类中具体代码都是在网上cv的
简单测试
Test.vue中的代码
<template>
<div>
<table>
<tr>
<td>编号</td>
<td>菜单名</td>
<td>父节点</td>
<td>请求编号</td>
</tr>
<tr v-for="(item,index) in tests">
<td>{{index}}</td>
<td>{{item.menuName}}</td>
<td>{{item.parentId}}</td>
<td>{{item.orderNum}}</td>
</tr>
</table>
</div>
</template>
<script>
import axios from "axios"
export default {
name: "Test",
data(){
return {
tests:[]
}
},
created() {
const _this = this
axios.get('http://localhost:8181/test/findAll').then(function (res){
console.log(res.data)
_this.tests = res.data
})
}
}
</script>
<style scoped>
</style>
在index.js中配置Test.vue的路由信息
index.js中的代码
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Test from '../views/Test.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path: '/test',
name: 'Test',
component: Test
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
分别运行SpringBoot项目和Vue项目,注意设置好端口,因为Vue项目和SpringBoot项目默认端口都是8080
成功访问并读取到数据
仓库地址:https://gitee.com/Sakurazjp/vue3_springboot