给我写一个 springboot + vue 的实战项目
时间: 2023-12-06 07:45:26 浏览: 103
Java毕业设计-基于springboot+vue的宠物爱心组织管理系统-付源代码+论文+mysql(大作业).zip
好的,下面给您提供一个简单的实战项目:使用SpringBoot + Vue.js构建一个简单的在线书店。
技术栈:
- 后端:SpringBoot、Spring Data JPA、MySQL
- 前端:Vue.js、ElementUI
功能实现:
- 用户注册、登录、退出登录
- 图书的CRUD操作(增删改查)
- 用户购买图书
1.搭建SpringBoot后端
首先,我们需要创建一个SpringBoot项目,然后添加以下依赖:
```
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
然后,创建图书实体类(Book.java)和用户实体类(User.java):
```java
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "author")
private String author;
@Column(name = "price")
private double price;
// 省略 getter 和 setter
}
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
// 省略 getter 和 setter
}
```
接着,创建图书仓库(BookRepository.java)和用户仓库(UserRepository.java):
```java
public interface BookRepository extends JpaRepository<Book, Long> {
}
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsernameAndPassword(String username, String password);
}
```
然后,创建一个RESTful API控制器(BookController.java),实现图书的CRUD操作:
```java
@RestController
@RequestMapping("/api/book")
public class BookController {
@Autowired
private BookRepository bookRepository;
@GetMapping("/")
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
@PostMapping("/")
public Book addBook(@RequestBody Book book) {
return bookRepository.save(book);
}
@PutMapping("/")
public Book updateBook(@RequestBody Book book) {
return bookRepository.save(book);
}
@DeleteMapping("/{id}")
public void deleteBook(@PathVariable Long id) {
bookRepository.deleteById(id);
}
}
```
最后,配置数据库连接信息(application.properties):
```
spring.datasource.url=jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
```
2.搭建Vue.js前端
首先,安装Vue CLI:
```
npm install -g @vue/cli
```
然后,创建Vue.js项目:
```
vue create bookstore-frontend
```
接着,安装ElementUI:
```
npm i element-ui -S
```
然后,创建一个图书列表组件(BookList.vue):
```vue
<template>
<div>
<el-table :data="books" style="width: 100%">
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="author" label="作者"></el-table-column>
<el-table-column prop="price" label="价格"></el-table-column>
</el-table>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
books: []
}
},
mounted () {
axios.get('/api/book/')
.then(res => {
this.books = res.data
})
.catch(err => {
console.log(err)
})
}
}
</script>
```
接着,创建一个添加图书的组件(AddBook.vue):
```vue
<template>
<div>
<el-form :model="book" label-width="80px">
<el-form-item label="名称">
<el-input v-model="book.name" placeholder="请输入名称"></el-input>
</el-form-item>
<el-form-item label="作者">
<el-input v-model="book.author" placeholder="请输入作者"></el-input>
</el-form-item>
<el-form-item label="价格">
<el-input v-model="book.price" placeholder="请输入价格"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="addBook">添加</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
book: {
name: '',
author: '',
price: ''
}
}
},
methods: {
addBook () {
axios.post('/api/book/', this.book)
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
}
}
}
</script>
```
最后,创建一个购物车组件(Cart.vue):
```vue
<template>
<div>
<el-table :data="cart" style="width: 100%">
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="price" label="价格"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button type="danger" size="mini" @click="removeBook(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-button type="primary" @click="buyBooks">购买</el-button>
</div>
</template>
<script>
export default {
props: {
cart: {
type: Array,
default: () => []
},
onBuy: {
type: Function
}
},
methods: {
removeBook (index) {
this.$emit('remove', index)
},
buyBooks () {
this.$emit('buy')
}
}
}
</script>
```
3.实现功能
现在,我们可以在Vue.js的入口文件(main.js)中添加路由和ElementUI的样式:
```js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
```
然后,创建一个路由配置文件(router.js):
```js
import Vue from 'vue'
import Router from 'vue-router'
import BookList from './views/BookList.vue'
import AddBook from './views/AddBook.vue'
import Cart from './views/Cart.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'book-list',
component: BookList
},
{
path: '/add-book',
name: 'add-book',
component: AddBook
},
{
path: '/cart',
name: 'cart',
component: Cart
}
]
})
```
然后,在App.vue中添加菜单和购物车组件:
```vue
<template>
<div id="app">
<el-menu :default-active="activeIndex" mode="horizontal" @select="handleSelect">
<el-menu-item index="/">图书列表</el-menu-item>
<el-menu-item index="/add-book">添加图书</el-menu-item>
<el-menu-item index="/cart">购物车</el-menu-item>
</el-menu>
<router-view :cart="cart" @remove="removeBook" @buy="buyBooks"></router-view>
</div>
</template>
<script>
export default {
data () {
return {
activeIndex: '/',
cart: []
}
},
methods: {
handleSelect (index) {
this.activeIndex = index
if (index === '/cart') {
this.getCart()
}
},
getCart () {
let cart = window.localStorage.getItem('cart')
if (cart) {
this.cart = JSON.parse(cart)
} else {
this.cart = []
}
},
removeBook (index) {
this.cart.splice(index, 1)
window.localStorage.setItem('cart', JSON.stringify(this.cart))
},
buyBooks () {
// TODO: 实现购买功能
}
},
mounted () {
this.getCart()
}
}
</script>
```
最后,在Cart.vue中实现购买功能:
```vue
<template>
<div>
<el-table :data="cart" style="width: 100%">
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="price" label="价格"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button type="danger" size="mini" @click="removeBook(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-button type="primary" @click="buyBooks">购买</el-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: {
cart: {
type: Array,
default: () => []
},
onBuy: {
type: Function
}
},
methods: {
removeBook (index) {
this.$emit('remove', index)
},
buyBooks () {
axios.post('/api/book/buy', this.cart)
.then(res => {
this.$message({
message: '购买成功',
type: 'success'
})
this.$emit('buy')
})
.catch(err => {
console.log(err)
})
}
}
}
</script>
```
至此,一个简单的在线书店就搭建完成了,您可以在这个基础上继续扩展其他功能。
阅读全文