返回
Vue、Springboot前后端分离项目搭建
前端
2023-11-06 02:24:50
前言
随着互联网的快速发展,前端和后端技术也日新月异。为了提高开发效率和项目的可维护性,前后端分离逐渐成为主流的开发模式。本文将介绍如何使用Vue和Springboot搭建前后端分离项目,涉及Vux、InlineCalendar、路由钩子、RESTful API等知识。
环境准备
在开始搭建项目之前,我们需要准备好开发环境。
- 操作系统:Windows、MacOS或Linux
- Node.js:>= 8.0.0
- npm:>= 5.0.0
- Java:>= 8.0.0
- Maven:>= 3.0.0
- IntelliJ IDEA:2019.2或更高版本
项目搭建
1. 创建Vue项目
首先,我们使用Vue CLI创建Vue项目。
vue create vue-spring-boot-project
2. 安装Vux
Vux是一个移动端UI库,提供了丰富的组件。
npm install vux
3. 创建Springboot项目
然后,我们使用Spring Initializr创建Springboot项目。
mvn spring-boot:generate-app \
--project-name spring-boot-project \
--package-name com.example \
--dependency spring-web \
--dependency spring-boot-starter-data-jpa \
--dependency mysql-connector-java \
--dependency spring-boot-starter-thymeleaf
4. 配置Vue项目
在Vue项目的package.json
文件中,添加以下依赖:
"axios": "^0.19.0",
"vue-router": "^3.0.1",
"vuex": "^3.0.1",
5. 配置Springboot项目
在Springboot项目的application.properties
文件中,添加以下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/vue_spring_boot_project
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
6. 编写代码
接下来,我们就可以编写代码了。
在Vue项目中,我们在src/main.js
文件中编写如下代码:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'
import App from './App.vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
Vue.use(VueRouter)
Vue.use(Vuex)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
在Vue项目的src/components/Home.vue
文件中,编写如下代码:
<template>
<div>
<h1>Home</h1>
<p>This is the home page.</p>
<button @click="increment">Increment count</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
data () {
return {
count: 0
}
},
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['increment']),
increment () {
this.$store.commit('increment')
}
}
}
</script>
在Springboot项目的src/main/java/com/example/SpringBootProjectApplication.java
文件中,编写如下代码:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
}
7. 运行项目
最后,我们可以运行项目了。
在Vue项目中,运行如下命令:
npm run serve
在Springboot项目中,运行如下命令:
mvn spring-boot:run
现在,我们就可以访问项目了。在浏览器中输入http://localhost:8080
,即可看到Vue项目的首页。
总结
本文介绍了如何使用Vue和Springboot搭建前后端分离项目,涉及Vux、InlineCalendar、路由钩子、RESTful API等知识。希望本文对读者有所帮助。