圖書管理系統Django+Vue
阿新 • • 發佈:2020-12-21
配置跨域Django和Vue點選
後端
-
圖書管理系統後端介面
-
1 books/models.py 中設定表
from django.db import models # Create your models here. from django.db import models class Books(models.Model): btitle = models.CharField(max_length=32) bpub_date = models.DateField() bread = models.IntegerField() bcomment =
-
urls.py 中設定路由
-
app/urls.py子路由
from django.urls import path from . import views urlpatterns = [ path('book/', views.BooksView.as_view()), ]
-
專案下/urls.py
"""djangoProject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """
-
-
book/views.py 檢視函式
from django.views import View from rest_framework.utils import json from .models import * # Create your views here. class BooksView(View): def
-
-
2.測試介面
-
測試獲取所有圖書介面
http://192.168.56.100:8888/books/book
-
測試建立圖書介面
新增資料 { "btitle":"dsad","bpub_date":"2020-10-29","bread":100,"bcomment":10 }
-
測試修改圖書介面
http://192.168.56.100:8888/books/book/
-
測試刪除資料介面 邏輯刪除
http://192.168.56.100:8888/books/book/
-
-
圖書管理vue頁面
-
http/apis.js 新增後端請求路由
/* eslint-disable */ import {get, post, put, del} from './index' // 書籍管理介面 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) ```
1.1 http/index.js 新增後端請求路由
/* eslint-disable */ // 第一步:例項化axios物件,簡單封裝 const axios = require('axios'); // 生成一個axios例項 axios.defaults.baseURL = 'http://192.168.56.100:8888'; // 設定請求後端的URL地址 axios.defaults.timeout = 10000; // axios請求超時時間 axios.defaults.withCredentials = true; axios.defaults.headers['Content-Type'] = 'application/json'; // axios傳送資料時使用json格式 axios.defaults.transformRequest = data => JSON.stringify(data); // 傳送資料前進行json格式化 // 第二:設定攔截器 /** * 請求攔截器(當前端傳送請求給後端前進行攔截) * 例1:請求攔截器獲取token設定到axios請求頭中,所有請求介面都具有這個功能 * 例2:到使用者訪問某一個頁面,但是使用者沒有登入,前端頁面自動跳轉 /login/ 頁面 */ axios.interceptors.request.use(config => { // 從localStorage中獲取token // let token = localStorage.getItem('token'); // 如果有token, 就把token設定到請求頭中Authorization欄位中 // token && (config.headers.Authorization = token); return config; }, error => { return Promise.reject(error); }); /** * 響應攔截器(當後端返回資料的時候進行攔截) * 例1:當後端返回狀態碼是401/403時,跳轉到 /login/ 頁面 */ axios.interceptors.response.use(response => { // 當響應碼是 2xx 的情況, 進入這裡 // debugger return response.data; }, error => { // 當響應碼不是 2xx 的情況, 進入這裡 // debugger return error }); /** * get方法,對應get請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function get(url, params, headers) { return new Promise((resolve, reject) => { // debugger axios.get(url, {params, headers}).then(res => { resolve(res) }).catch(err => { reject(err) }) }) } // 第三:根據上面分裝好的axios物件,封裝 get、post、put、delete請求 /** * post方法,對應post請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] **/ export function post(url, params, headers) { return new Promise((resolve, reject) => { axios.post(url, params, headers).then((res) => { resolve(res) }).catch((err) => { // debugger reject(err) }) }) } export function put(url, params, headers) { return new Promise((resolve, reject) => { axios.put(url, params, headers).then((res) => { resolve(res) }).catch((err) => { // debugger reject(err) }) }) } export function del(url, params, headers) { return new Promise((resolve, reject) => { axios.delete(url, {data: params, headers}).then((res) => { resolve(res) }).catch((err) => { // debugger reject(err) }) }) } export default axios;
-
router/index.js 新增路由
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Books from '@/views/books/Books' import Father from "../components/Father"; import Login from "../views/Login"; Vue.use(Router) export default new Router({ routes: [ {path: '/', name: 'Books', component: Books}, // 圖書增刪改查 ] })
-
src\views\books\Books.vue 父元件
<template> <div> <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> </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: { addNew() { this.editData = { // 初始化 編輯內容 btitle: "", bpub_date: "", bread: 100, bcomment: 0 } this.dialogVisible = true // 顯示彈框 }, // 2.獲取圖書列表 get() { getBookList().then((data) => { console.log(123123123123) 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>
-
- src\components\BookEdit.vue 子元件
<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>
.elinput {
width: 220px;
height: 40px;
}
</style>
-
src/mian.js 引入ElementUI
// 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/>' }) 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/>' })
展示