項目使用技術:
Node.js + MongoDB + Vue + axios
使用刪除的場景是,表格中一行行的刪除動作。
<el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">刪除</el-button>
這個看起來比較簡單的動作,在使用 new Promise 封裝 delete 方法時,始終獲取不到傳過來的 id。在調試過程中發現 resolve 的內容一直輸出一個 new Promise 對象,而傳的 id 一直獲取不到,Node.js 一直報500錯,我一開始以為是 接口寫的有問題,經過調試發現沒傳過來要刪除的id.
前端 del 封裝,這是正確的寫法
/** * delete方法,對應delete請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的參數] */ export function del(url,params){ return new Promise( async (resolve, reject) => { await axios.delete(url, { params }).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) }
問題就出在上面的代碼塊中,有兩個錯誤:
- 沒有給 new Promise 使用 async / await
- params 獲取參數方式錯誤
在 Vue 中,刪除方法是使用 Element $confirm 方法,這個方法的 Options.callback 官方中關於回調是這樣解說的 【若不使用 Promise,可以使用此參數指定 MessageBox 關閉后的回調】。但是我是用 Promise 的,因此用不着 callback 。
經過修過,現在正確的寫法是:
handleDel(index,row){ this.id = row._id this.$confirm('是否確認要刪除?', '提示',{ confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }) .then( async () => { await apiDelTitle({id:this.id}); this.$message({ type:'success', message:'刪除成功' }) }).catch(() => { this.$message({ type: 'info', message: '已取消刪除' }) }) }
這里也出現了問題:
- 在使用 $confirm 后,在它的回調中,就是 .then() 方法中要使用 async / await ,因為我要在 彈框關閉后 調用刪除接口。
- 調用刪除接口傳的是一個對象,在封裝 del 時,params 要作為一個對象接收 id
困擾的問題解決了,前后端代碼貼在這里記錄一下。
前端:
del.js
/** * delete方法,對應delete請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的參數] */ export function del(url,params){ return new Promise( async (resolve, reject) => { await axios.delete(url, { params }).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) }
api.js
import {del} from './del'
export const apiDelTitle = params => del('/users/title',params)
vue
<el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">刪除</el-button> handleDel(index,row){ this.id = row._id this.$confirm('是否確認要刪除?', '提示',{ confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }) .then( async () => { await apiDelTitle({id:this.id});
//刪除數據成功后,重新獲取數據 this.getData() this.$message({ type:'success', message:'刪除成功' }) }).catch(() => { this.$message({ type: 'info', message: '已取消刪除' }) }) }
接口部分
Schema
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const userTitleSchema = new Schema({
titleName:String,
uid:Number,
type:String,
size:Number,
fileName:String,
createAt: {
type: Date,
default: Date.now()
},
updateAt: {
type: Date,
default: Date.now()
}
})
module.exports = userTitleSchema
models
var mongoose = require('mongoose') var userTitleSchema = require('../../schemas/user/userTitel') var UserTitle = mongoose.model('UserTitle',userTitleSchema) module.exports = UserTitle
router( 接口方法 )
var express = require('express') var userTitleRouter = express.Router() var UserTitle = require('../../models/user/userTitle') userTitleRouter.route('/title') .delete((req, res) => { var _id = `${req.query.id}`; UserTitle.findById({ _id }).then((doc) => { if (!doc) { res.status(400).json({ message: `${doc} 不存在` }) } else { UserTitle.deleteOne({ _id }).then(title => res.status(200).json({ message: `${title} 刪除成功` })).catch(err => { console.log(err) }) } }) }) module.exports = userTitleRouter
app.js
var users = require('./routes/users/index') //使用 use 中間件處理前端的請求 app.use('/api/users', usersTitle)
如果大家有更好的辦法,歡迎留言。
項目地址
