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