vue实现图书管理案例
Vue 实现图书管理案例
项目初始化
使用 Vue CLI 创建项目,安装必要依赖。
vue create book-management
cd book-management
npm install axios vue-router --save
数据结构设计
图书数据通常包含标题、作者、ISBN、出版日期等字段。
// src/data/books.js
export default [
{ id: 1, title: 'Vue.js实战', author: '张三', isbn: '9787121371234', publishDate: '2020-01-01' },
{ id: 2, title: 'JavaScript高级编程', author: '李四', isbn: '9787115275790', publishDate: '2019-05-15' }
]
核心组件实现
创建图书列表组件 BookList.vue:

<template>
<div>
<table>
<thead>
<tr>
<th>书名</th>
<th>作者</th>
<th>ISBN</th>
<th>出版日期</th>
</tr>
</thead>
<tbody>
<tr v-for="book in books" :key="book.id">
<td>{{ book.title }}</td>
<td>{{ book.author }}</td>
<td>{{ book.isbn }}</td>
<td>{{ book.publishDate }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
books: []
}
},
created() {
this.fetchBooks()
},
methods: {
fetchBooks() {
// 实际项目中应调用API
this.books = require('@/data/books')
}
}
}
</script>
路由配置
在 src/router/index.js 中配置路由:
import Vue from 'vue'
import Router from 'vue-router'
import BookList from '@/components/BookList'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/', component: BookList }
]
})
添加图书功能
创建 AddBook.vue 组件:

<template>
<div>
<form @submit.prevent="addBook">
<input v-model="newBook.title" placeholder="书名">
<input v-model="newBook.author" placeholder="作者">
<input v-model="newBook.isbn" placeholder="ISBN">
<input v-model="newBook.publishDate" type="date">
<button type="submit">添加</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
newBook: {
id: Date.now(),
title: '',
author: '',
isbn: '',
publishDate: ''
}
}
},
methods: {
addBook() {
this.$emit('book-added', this.newBook)
this.resetForm()
},
resetForm() {
this.newBook = {
id: Date.now(),
title: '',
author: '',
isbn: '',
publishDate: ''
}
}
}
}
</script>
状态管理(可选)
对于复杂应用,可以使用 Vuex 管理状态:
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
books: []
},
mutations: {
ADD_BOOK(state, book) {
state.books.push(book)
}
},
actions: {
addBook({ commit }, book) {
commit('ADD_BOOK', book)
}
}
})
API 集成
实际项目中应连接后端 API:
// src/api/bookService.js
import axios from 'axios'
export default {
getBooks() {
return axios.get('/api/books')
},
addBook(book) {
return axios.post('/api/books', book)
}
}
项目结构建议
src/
├── components/
│ ├── BookList.vue
│ ├── AddBook.vue
├── views/
├── router/
├── store/
├── api/
├── assets/
样式优化
使用 CSS 或 UI 框架(如 Element UI)美化界面:
<template>
<el-table :data="books">
<el-table-column prop="title" label="书名"></el-table-column>
<el-table-column prop="author" label="作者"></el-table-column>
</el-table>
</template>
