antdv中this.$confirm 里面拿不到this

2021-09-17  本文已影响0人  NemoExpress

Ant Design Vue 中使用 this.$confirm 时,this调用data数据和方法都失败,提示是该方法未定义。

问题: 确认框点击确认后需要执行一些方法,发现报错

确认框点击确认
报错

代码如下:


确认框逻辑代码

解决方案

方案1:在确认框中用到的当前作用域时,this需要提前替换为局部变量,否则浏览器会提示无法获取该属性

goDel(r) 
      const self = this // 提前保存this
      this.$confirm({
        title: '你确定要删除该条记录吗?',
        content: con,
        onOk() {
          return delBpoint({ id: r.idPoint, uuid: r.vmUuid })
            .then(res => {
              console.log(res, 'lalal', this)
              // 成功过后刷新
              self.$refs.imgtable.refresh() // 使用self代替this调用
            })
            .catch(e => console.log('删除失败', e))
        },
        onCancel() {}
      })
    },

方案2:将确认按钮的onOk的方法改成es6箭头函数

 goDel(r) {
      this.$confirm({
        title: '你确定要删除该条记录吗?',
        content: con,
        onOk: () => { // 改成箭头函数后this就能直接使用
          return delBpoint({ id: r.idPoint, uuid: r.vmUuid })
            .then(res => {
              console.log(res, 'lalal', this)
              // 成功过后刷新
              this.$refs.imgtable.refresh()
            })
            .catch(e => console.log('删除失败', e))
        },
        onCancel() {}
      })
    },
上一篇 下一篇

猜你喜欢

热点阅读