图书管理曾删改差
1.图书管理系统后端接口
1.1books/models.py 中设置表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models class Books(models.Model): btitle = models.CharField(max_length=20) bpub_date = models.DateField() bread = models.IntegerField() bcomment = models.IntegerField() is_delete = models.BooleanField(default=False)
1.2urls.py中设置路由
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.urls import path from . import views urlpatterns = [ path('book/', views.BooksView.as_view()), ]
1.3 book/views.py视图函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.http import JsonResponse import json from rest_framework.views import View from .models import * class BooksView(View): def get(self, request): books = Books.objects.filter(is_delete=False) book_list = books.values('id', 'btitle', 'bpub_date', 'bread', 'bcomment') book_list = list(book_list) data = { "code":0, "msg":"success", "books":book_list } return JsonResponse(data) def post(self,request): body_json = request.body.decode() body_dict = json.loads(body_json) btitle = body_dict.get('btitle') bpub_date = body_dict.get('bpub_date') bread = body_dict.get('bread') bcomment = body_dict.get('bcomment') book = Books(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment) book.save() return JsonResponse({"code": 0, "msg": "success"}) def put(self, request): body_json = request.body.decode() body_dict = json.loads(body_json) id = body_dict.get('id') btitle = body_dict.get('btitle') bpub_date = body_dict.get('bpub_date') bread = body_dict.get('bread') bcomment = body_dict.get('bcomment') book = Books.objects.get(id=id) book.btitle = btitle book.bpub_date = bpub_date book.bread = bread book.bcomment = bcomment book.save() return JsonResponse({"code": 0, "msg": "success"}) def delete(self, request): body_json = request.body.decode() body_dict = json.loads(body_json) id = body_dict.get('id') book = Books.objects.get(id=id) book.is_delete = True book.save() return JsonResponse({"code": 0, "msg": "success"})
查询
http://127.0.0.1:8000/books/book/
添加
http://127.0.0.1:8000/books/book/
{ "btitle": "我真不是大魔王05", "bpub_date": "2018-02-04", "bread": 100, "bcomment": 0 }
修改
http://127.0.0.1:8000/books/book/
{ "id": 1, "btitle": "红楼梦", "bpub_date": "2018-02-04", "bread": 100, "bcomment": 0 }
删除
http://127.0.0.1:8000/books/book/
{ "id": 1, "btitle": "红楼梦", "bpub_date": "2018-02-04", "bread": 100, "bcomment": 0 }
2 图书管理前端页面
1.1 http/apis.js添加后端请求路由
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import { get, post, put, del } from './index' // 用户登录 export const login = (params, headers) => post("/login/", params, headers) export const getBookList = (params, headers) => get("/books/book/", params, headers) export const addBook = (params, headers) => post("/books/book/", params, headers) export const editBook = (params, headers) => put("/books/book/", params, headers) export const delBook = (params, headers) => del("/books/book/", params, headers)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import axios from 'axios' axios.defaults.baseURL = "http://127.0.0.1:8000/" // axios.defaults.baseURL = "http://192.168.56.100:8888/" //全局设置网络超时 axios.defaults.timeout = 10000; //设置请求头信息 axios.defaults.headers.post['Content-Type'] = 'application/json'; axios.defaults.headers.put['Content-Type'] = 'application/json'; axios.interceptors.request.use( config => { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了 const token = localStorage.getItem("token") // console.log(token) if (token) { config.headers.Authorization = 'JWT ' + token } return config; }, error => { return Promise.error(error); }) axios.interceptors.response.use( // 请求成功 res => (res.status === 200 || res.status === 201) ? Promise.resolve(res) : Promise.reject(res), // 请求失败 error => { if (error.response) { // 判断一下返回结果的status == 401? ==401跳转登录页面。 !=401passs // console.log(error.response) if (error.response.status === 401) { // 跳转不可以使用this.$router.push方法、 // this.$router.push({path:'/login'}) window.location.href = "http://127.0.0.1:8888/" } else { // errorHandle(response.status, response.data.message); return Promise.reject(error.response); } // 请求已发出,但是不在2xx的范围 } else { // 处理断网的情况 // eg:请求超时或断网时,更新state的network状态 // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏 // 关于断网组件中的刷新重新获取数据,会在断网组件中说明 // store.commit('changeNetwork', false); return Promise.reject(error.response); } }); // 封装xiaos请求 // 封装get请求 export function axios_get(url, params) { return new Promise( (resolve, reject) => { axios.get(url, { params: params }) .then(res => { // console.log("封装信息的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) } // 封装post请求 export function axios_post(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.post(url, JSON.stringify(data)) .then(res => { // console.log("封装信息的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) } // 封装put请求 export function axios_put(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.put(url, JSON.stringify(data)) .then(res => { // console.log("封装信息的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) } // 封装delete请求 export function axios_delete(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.delete(url, { params: data }) .then(res => { // console.log("封装信息的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) }
1.2 router/index.js添加路由
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import BookEdit from '@/components/BookEdit' import Books from '@/views/books/Books' { path:'/books', name:'Books', component:Books }, { path:'/bookEdit', name:'BookEdit', component:BookEdit },
1.3 src\views\books\Books.vue父组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div> <h1>图书管理系统</h1> <div style="margin:30px;"> <button @click="addNew">新增图书</button> <BookEdit v-show="dialogVisible" :visible.sync='dialogVisible' :data='editData' @save='save' > </BookEdit> </div> <div> <table style='margin: auto; border: solid 1px black;'> <tr> <th>图书编号</th> <th>图书名子</th> <th>出版时间</th> <th>阅读数</th> <th>评论数</th> <th>操作</th> </tr> <tr v-for="(book,index) in books" :key="book.id"> <td>{{book.id}}</td> <td>{{book.btitle}}</td> <td>{{book.bpub_date}}</td> <td>{{book.bread}}</td> <td>{{book.bcomment}}</td> <td> <button @click="edit(index)">修改</button> <button @click="del(index)">删除</button> </td> </tr> </table> </div> </div> </template> <script> import { getBookList, addBook, editBook, delBook } from '@/http/apis' import BookEdit from '@/components/BookEdit' export default { components:{ BookEdit }, data(){ return{ dialogVisible:false, books:[ { id: 3, btitle: "...", bpub_date: "2020-08-11", bread: 100, bcomment: 50 } ], editData:{ // 编辑的内容 btitle: "", bpub_date: "", bread: 0, bcomment: 0 } } }, methods:{ //1.点击新增图书时初始化数据 addNew(){ this.editData={ // 初始化 编辑内容 btitle: "", bpub_date:'', bread: 100, bcomment: 0 } this.dialogVisible=true //显示弹框 }, //2.获取图书列表 get(){ getBookList().then((data) => { // console.log(data) // books: [{btitle: "西游记", bpub_date: "2020-08-11", bread: 100, bcomment: 50}] this.books = data.books }) }, //3 修改或者添加图书 save(){ // 根据editData中的id判断是更新还是新增 // debugger console.log(this.editData) if (this.editData.id) { // 如果有id, 修改图书 //修改请求 let params = this.editData editBook(params).then((res)=>{ console.log(res) this.get() }) } else { //增加图书 addBook(this.editData).then((res) => { this.get() })} }, //点击修改弹出修改页面 edit(index){ this.editData=JSON.parse(JSON.stringify(this.books[index])) // 复制this.books[index] 的数据 // this.editData = this.books[index] // this.dialogVisible = true }, //删除 del(index){ let params={ id: this.books[index].id } delBook(params).then((res)=>{ console.log(res) this.get() })} }, created(){ this.get() } } </script> <style scoped> table tr td{ width: 150px; border:solid 1px black; } </style>
1.4 src\components\BookEdit.vue子组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div> <el-dialog title="新增图书" :visible="visible" > <div> <span>图书名称:</span> <el-input class="elinput" v-model="data.btitle" ></el-input> </div> <div> <span>发布日期:</span> <el-input class='elinput' v-model="data.bpub_date" ></el-input> </div> <div> <span>阅读量:</span> <el-input class='elinput' v-model="data.bread" ></el-input> </div> <div> <span>评论量:</span> <el-input class="elinput" v-model="data.bcomment" ></el-input> </div> <el-button @click="cancel">取消</el-button> <el-button type="primary" @click="addBook" >确定 </el-button> </el-dialog> </div> </template> <script> // import { addbook } from '@/http/apis' export default { props: ['data', 'visible'], data(){ return{ } }, methods:{ addBook(){ this.$emit('update:visible', false) this.$emit('save') }, cancel(){ this.$emit('update:visible', false) } }, mounted(){ } } </script> <style scoped> .eliput{ width: 220px; height: 40px; } </style>
1.5 src/mian.js引入ElementUl
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false // 使用 elementui // npm i element-ui -S 安装到当前项目 import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })