zoukankan      html  css  js  c++  java
  • 正确使用 Element $confirm 方法,联调删除接口

    项目使用技术:

    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)
            })
        })
    }

    问题就出在上面的代码块中,有两个错误:

    1. 没有给 new Promise 使用 async / await 
    2. 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: '已取消删除'
                    })
                })
            }

    这里也出现了问题:

    1. 在使用 $confirm 后,在它的回调中,就是 .then() 方法中要使用 async / await ,因为我要在 弹框关闭后 调用删除接口。
    2. 调用删除接口传的是一个对象,在封装 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)

    如果大家有更好的办法,欢迎留言。

    项目地址

  • 相关阅读:
    c字符指针与字符数组的区别
    BiLstm原理
    TensorFlow中assign函数
    TensorFlow Training 优化函数
    TensorFlow 神经网络相关函数
    TensorFlow 算术运算符
    TensorFlow函数:tf.reduce_sum
    TensorFlow函数教程:tf.nn.dropout
    TensorFlow占位符操作:tf.placeholder_with_default
    TensorFlow函数:tf.random_shuffle
  • 原文地址:https://www.cnblogs.com/baiyygynui/p/13762632.html
Copyright © 2011-2022 走看看