美文网首页
antdv中this.$confirm 里面拿不到this

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

作者: NemoExpress | 来源:发表于2021-09-17 11:41 被阅读0次

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() {}
      })
    },

相关文章

网友评论

      本文标题:antdv中this.$confirm 里面拿不到this

      本文链接:https://www.haomeiwen.com/subject/rpvjgltx.html