最近嘗試使用vue+element實現增刪改查功能,在實現的過程當中遇到了蠻多問題,如今總結以下:
首先安裝相關的插件
一、根據vue官網推薦,使用axios進行先後臺交互,安裝axios
npm install axios -S
二、安裝elementUI,官網
npm i element-ui -S
三、安裝 loader 模塊
npm install style-loader -D
npm install css-loader -Dcss
接下來進行相關配置
一、在build目錄下的webpack.base.conf.js文件中添加以下代碼
{前端
test: /\.sass$/, loaders: ['style', 'css', 'sass']
}
二、在main.js中引入
import ElementUI from ‘element-ui‘
import ‘element-ui/lib/theme-default/index.css‘
Vue.use(ElementUI)vue
接下來實現增刪改查功能
貼出table.vue(目前實現了增、刪兩個功能)webpack
<template> <section> <el-col :span="24" class="toolbar" style="padding-bottom: 0; text-align: left"> <el-form :inline="true" :model="filters"> <el-form-item> <el-input v-model="filters.author" placeholder="做者"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="getUsers">查詢</el-button> </el-form-item> <el-form-item> <el-button type="primary" @click="handleAdd">新增</el-button> </el-form-item> </el-form> </el-col> <!--爲了實現分頁bookData.slice((currentPage-1)*pageSize,currentPage*pageSize)--> <el-col :span="24" style="background: #ff0"> <el-table border :data="bookData.slice((currentPage-1)*pageSize,currentPage*pageSize)" :loading="listLoading" @selection-change="selectionRowsChange" style="width: 100%; text-align: left;"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column type="index" label="#" width="60"></el-table-column> <el-table-column prop="author" label="做者" width="200"></el-table-column> <el-table-column prop="title" label="書名" width="200"></el-table-column> <el-table-column prop="price" label="單價" width="120"></el-table-column> <el-table-column prop="publish" label="出版社" width="200"></el-table-column> <el-table-column prop="publishDate" label="出版日期"></el-table-column> <el-table-column label="操做" width="250"> <template slot-scope="scope"> <!--由elementui提供,scope.$index和scope.row是爲了方便與後臺進行數據交互,後面的刪除函數中會用到--> <el-button size="mini">編輯</el-button> <el-button size="mini" type="danger" @click="removeUser(scope.$index, scope.row)">刪除</el-button> </template> </el-table-column> </el-table> </el-col> <el-col :span="24" style="margin-top: 20px; text-align: left"> <el-button type="danger" @click="batchesRemove"> 批量刪除 </el-button> <el-pagination background layout="total, prev, pager, next, jumper" :total= "total" :page-size="pageSize" @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page.sync="currentPage" style="float: right;"></el-pagination> </el-col> <!--增長書本內容--> <el-dialog title="新增書籍" :visible.sync="dialogCreateVisible" style="text-align: left"> <el-form :rules="addFormRules" ref="addForm" :model="addForm" :label-width="addFormLabelWidth"> <el-form-item label="做者" prop="author"> <el-input v-model="addForm.author" name="author" auto-complete="off"></el-input> </el-form-item> <el-form-item label="書名" prop="title"> <el-input v-model="addForm.title" name="title" auto-complete="off"></el-input> </el-form-item> <el-form-item label="單價" prop="price"> <el-input v-model="addForm.price" name="price" auto-complete="off"></el-input> </el-form-item> <el-form-item label="出版社" prop="publish"> <el-input v-model="addForm.publish" name="publish" auto-complete="off"></el-input> </el-form-item> <el-form-item label="出版日期" prop="publishDate"> <!--<el-input v-model="addForm.publishDate"></el-input>--> <el-date-picker v-model="addForm.publishDate" name="publishDate" type="date" placeholder="選擇日期"></el-date-picker> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="createReset">取消</el-button> <el-button @click.native="createSubmit" :loading="addLoading" type="primary">肯定</el-button> </div> </el-dialog> <!--編輯書本信息--> <el-dialog title="修改書本信息" :visible.sync="dialogUpdateVisible" :close-on-click-modal="false" style="text-align: left"> <el-form :model="updateForm" :rules="updateRules" ref="update" label-width="100px"> <el-form-item label="做者" prop="authorName"> <el-input v-model="updateForm.authorName"></el-input> </el-form-item> <el-form-item label="書名" prop="title"> <el-input v-model="updateForm.title"></el-input> </el-form-item> <el-form-item label="單價" prop="price"> <el-input v-model="updateForm.price"></el-input> </el-form-item> <el-form-item label="出版社" prop="publish"> <el-input v-model="updateForm.publish"></el-input> </el-form-item> <el-form-item label="出版日期" prop="publishDate"> <!--<el-input v-model="updateForm.publishDate"></el-input>--> <el-date-picker type="date" placeholder="選擇日期" v-model="updateForm.publishDate"></el-date-picker> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="editReset">取消</el-button> <el-button type="primary" :loading="updateLoading" @click.native="editSubmit">肯定</el-button> </div> </el-dialog> </section> </template> <script> export default { name: "add", data() { return { bookData: [], filters: { author: '', }, total: 0, pageSize: 0, currentPage: 1, listLoading: false, sels: [], // 選中的列 // 新增表單 addForm: { author: '', title: '', price: '', publish: '', publishDate: '' }, addFormRules: { author: [ { required: true, message: '請輸入做者', trigger: 'blur'} ], title: [ { required: true, message: '請輸入書名', trigger: 'blur'} ], price: [ { required: true, message: '請輸入書本單價 ', trigger: 'blur' }, { pattern: /^\d+(\.\d{1,2})?$/, message: '單價必須爲數字,而且小數點後不超過兩位', trigger: 'blur' } ], publish: [ { required: true, message: '請輸入出版社名', trigger: 'blur' } ] }, dialogCreateVisible: false, addFormLabelWidth: '80px', addLoading: false, // 編輯表單 updateForm: { authorName: '', title: '', price: '', publish: '', publishDate: '' }, updateRules: { authorName: [{ message: '請輸入姓名', trigger: 'blur', }, { min: 3, max: 15, message: '長度在3-15個字符' }], title: [{ message: '請輸入書名' }], price: [{ type: 'number', // pattern: '', message: '請輸入最多兩位小數的單價' }] }, updateLoading: false, dialogUpdateVisible: false // 編輯對話框的顯示狀態 } }, methods: { // 改變頁碼 handleCurrentChange(val) { this.currentPage = val; this.getUsers(); }, // 改變每頁顯示的數量 handleSizeChange(val) { this.pageSize = val; }, // 查詢, 獲取用戶列表 getUsers() { // 使用URLSearchParams函數的緣由:在與後臺進行交互時,若是後臺使用的字符編碼格式與axios的編碼格式不一致,會致使後端不能接收到前端傳過去的參數,爲了解決這一問題, let para = new URLSearchParams(); para.append("author", this.filters.author); this.listLoading = true; this.$ajax({ methods: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/bookList', data: para, }).then(res => { this.total = res.data.length; this.pageSize = 20; // 每頁展現的條目數 this.author = res.data[0].author; // 將後臺傳過來的數據填充到前端表單頁面中 this.bookData = res.data; this.listLoading = false; }).catch( err => { console.log(err); }) }, // 顯示新增 handleAdd () { this.dialogCreateVisible = true; this.addForm = { author: '', title: '', price: '', publish: '', publishDate: '' }; }, // 提交新增書籍信息 createSubmit() { this.$refs.addForm.validate((valid) => { if (valid) { this.$confirm('確認提交?', '提示', {}).then(() => { this.addLoading = true; let addPara = new URLSearchParams(); addPara.append("id", this.addForm.id); addPara.append("title", this.addForm.title); addPara.append("author", this.addForm.author); addPara.append("price", this.addForm.price); addPara.append("publish", this.addForm.publish); addPara.append("publishDate", this.addForm.publishDate); this.$ajax({ method: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/addBook', data:addPara, }).then(res => { console.log(eval("("+res.data+")")); console.log(addPara); console.log(addPara.author); console.log(res.data); this.addLoading = false; this.$message({ type: 'success', message: '提交成功!' }); this.dialogCreateVisible = false; this.getUsers(); }) }).catch(() => { this.$message({ type: 'info', message: '已取消新增' }); }) } else { console.log('error'); return false; } }) }, // 顯示編輯頁面 handleEdit(index, row) { console.log('click success'); this.dialogUpdateVisible = true; // this.updateForm = Object.assign({}, row) let updateParas = new URLSearchParams(); updateParas.append("id", row.id); this.$ajax({ method: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/loadBook', data: updateParas }).then(res => { this.updateForm = res.data; }) }, // 編輯頁面重置 createReset() { this.dialogCreateVisible = false; this.$refs.addForm.resetFields(); }, // 提交編輯後書籍信息 editSubmit() { this.$refs.update.validate((valid) => { if (valid) { this.$confirm('確認提交?', '提示', {}).then(() => { this.addLoading = true; let editParas = new URLSearchParams(); editParas.append("id", this.updateForm.id); editParas.append("author", this.updateForm.author); editParas.append("title", this.updateForm.title); editParas.append("price", this.updateForm.price); editParas.append("publish", this.updateForm.publish); editParas.append("publishDate", this.updateForm.publishDate); this.$ajax({ method: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/updateBook', data: editParas }).then(res => { console.log(res.data); // this.bookData = res.data; this.updateLoading = false; this.$message({ type: 'success', message: '提交成功!' }); this.dialogUpdateVisible = false; this.getUsers(); }) }).catch(() => { this.$message({ type: 'info', message: '已取消編輯' }); }) } }) }, // 單個刪除書籍信息 removeUser(index, row) { this.$confirm('肯定刪除該記錄嗎? ', '提示', { type: 'warning' }).then(() => { this.listLoading = true; let delParas = new URLSearchParams(); delParas.append("id", row.id ); // 響應template中scope.row,實現向後臺傳送當前row的id // 向服務端請求刪除 this.$ajax({ method: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/delectBook', data:delParas, }).then(res => { this.listLoading = false; this.$message({ message: '刪除成功', type: 'success' }); this.getUsers(); }); }).catch(() => { console.log('刪除失敗'); }) }, // 選擇選中的行 selectionRowsChange(sels) { // 將選中的行放進sels數組 this.sels = sels; }, // 批量刪除書籍 batchesRemove() { // 將數組轉化string類型 var idArray = this.sels.map(item => item.id).toString(); this.$confirm('確認刪除選中記錄嗎?', '提示', { type: 'warning', }).then(() => { let batchPara = new URLSearchParams(); batchPara.append("idArray", idArray); this.$ajax({ method: 'post', url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/batchDeleting', data: batchPara }).then((res) => { this.$message({ message: '刪除成功', type: 'success' }); this.getUsers(); }) }).catch(() => {}) }, }, // mounted的做用就是保證在進入table.vue文件時就加載用戶數據 mounted() { this.getUsers(); } } </script> <style scoped type="scss"> .el-table td { text-align: left; } </style>
上面代碼中最重要的一點是後臺可能接收不到前端數據,解決方案代碼中已經給出,具體緣由沒有寫明,你們想看能夠看
https://blog.csdn.net/csdn_yu...
這篇博客寫的比較清楚
我採用的是第一種方法:
在main.js文件中添加
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
而後在調用接口時使用 URLSearchParams 傳遞參數,例如獲取用戶數據時
let para = new URLSearchParams();
para.append("author", this.filters.author); // append中的author、id、idArray都是要和後臺提供的參數相同,否則數據參數將傳不過去
this.$ajax({
methods: 'post',
url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/bookList',
data: para,
}).then(res => {
console.log(res);
}).catch( err => {
console.log(err);
})ios
其實,實現增刪改查最重要的是在找到正確的參數,並將參數傳遞給後臺,功能的實現主要是後臺,前端只負責數據展現。
增刪改查功能所有實現。web