
1. 配置import { defineConfig } from vite import vue from vitejs/plugin-vue import { resolve } from path export default defineConfig({ plugins: [vue()], resolve: { alias: { : resolve(__dirname, src) } }, server: { proxy: { /api: { target: http://127.0.0.1:8000, changeOrigin: true, } } } })Vue 前端配置在/api路徑下配置代理將請求轉發到后端地址 http://127.0.0.1:8000/api/changeOrigin: true修改請求頭中的Origin為目標地址避免后端因 Origin 校驗拒絕請求。2. 接口格式// 加載圖書列表 1. 在掛載時加載 // const loadBook () { // axios.get(/api/book/?page${query.value.page}page_size${query.value.page_size}) // .then(res { // console.log(后端返回, res.data) // tableData.value res.data.data // totalNum.value res.data.count_total // }) // .catch(err console.error(err)) // }1. 方法一axios.get(調用路徑/?分頁參數 查詢條件).then請求成功后觸發.then中的回調函數。.catch請求失敗后觸發。相當于一個 if-else 判斷如果成功執行成功邏輯如果失敗則提示錯誤。2. 方法二// 加載圖書列表 2. 在事件中加載 const loadBook () { axios.get(/api/book/, {params: query.value}) .then(res { console.log(res.data) tableData.value res.data.data totalNum.value res.data.count_total }) .catch(err console.error(err)) }在事件中加載時將參數放在請求體{params: query.value}中params中傳遞數據不在路由中傳遞。3. 添加、編輯接口!-- 新增、編輯共用彈窗 -- el-dialog v-modeldialogVisible title圖書表單 width520px el-form label-width90px el-form-item label書名 el-input v-modelform.name/el-input /el-form-item el-form-item label價格 el-input v-model.numberform.price/el-input /el-form-item el-form-item label庫存數量 el-input v-model.numberform.numbers/el-input /el-form-item !-- 分類下拉選擇 -- el-form-item label分類 el-select v-modelform.category_id placeholder請選擇分類 stylewidth: 100% el-option label文學小說 value1 / el-option label計算機編程 value2 / el-option label歷史人文 value3 / el-option label心理學 value4 / el-option label美食菜譜 value5 / /el-select /el-form-item /el-form template #footer el-button clickdialogVisible false取消/el-button el-button typeprimary clicksubmitForm確定提交/el-button /template /el-dialog組件定義彈窗變量dialogVisible false默認未打開點擊后打開并顯示數據綁定form中的空數據。如果輸入數據就將輸入的數據放到form中對應的字段中。添加接口、編輯接口const submitForm () { if (operateMode.value add) { // 新增 axios.post(/api/book/, form.value) .then(() { ElMessage.success(新增成功) dialogVisible.value false loadBook() }) .catch(err { ElMessage.error(新增失敗) console.error(err) }) } else { // 編輯 axios.put(/api/book/${editBookId.value}, form.value) .then(() { ElMessage.success(修改成功) dialogVisible.value false loadBook() }) .catch(err { ElMessage.error(修改失敗) console.error(err) }) } }因為編輯和添加功能在一起需要先判斷當前窗口是添加還是編輯然后調用對應的接口。將請求體發送到后端form中是添加的數據傳到后端后添加到 MySQL 數據庫中。添加或編輯成功后將dialogVisible.value false關閉窗口。修改時只傳遞修改后的數據然后傳到后端接口進行修改。