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

Ant Design Vue 中使用 this.$confirm 時,this調(diào)用data數(shù)據(jù)和方法都失敗,提示是該方法未定義。

問題: 確認(rèn)框點擊確認(rèn)后需要執(zhí)行一些方法,發(fā)現(xiàn)報錯

確認(rèn)框點擊確認(rèn)

報錯

代碼如下:


確認(rèn)框邏輯代碼

解決方案

方案1:在確認(rèn)框中用到的當(dāng)前作用域時,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調(diào)用
            })
            .catch(e => console.log('刪除失敗', e))
        },
        onCancel() {}
      })
    },

方案2:將確認(rèn)按鈕的onOk的方法改成es6箭頭函數(shù)

 goDel(r) {
      this.$confirm({
        title: '你確定要刪除該條記錄嗎?',
        content: con,
        onOk: () => { // 改成箭頭函數(shù)后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() {}
      })
    },
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容