期望:
beforeRemoveRow执行异步操作(转到数据库),然后返回false / true。如果是'false',我希望不要从表中删除该行。
行为:
即使我从beforeRemoveRow返回'false',该行也会被删除。
代码:
与Vue.js合作
<template>
<!-- ... -->
</template>
<script>
import { mapState } from 'vuex'
import hot from '@/components/hot/index'
import { url } from '@/constants/api'
export default {
computed: {
...mapState({
clientAccounts: state => state.clients.clientAccounts,
token: state => state.auth.token
})
},
data () {
return {
hotSettings: {
beforeRemoveRow: async (index) => {
const confirmed = confirm('Do you really want to delete the user?')
if (confirmed) {
try {
const result = await this.$store.dispatch({
type: 'deleteClientAccount',
id: this.clientAccounts[index].id,
token: this.token,
})
console.log('result', result)
return true
} catch (err) {
return false
}
} else {
return false
}
},
contextMenu: ['remove_row']
}
}
},
components: {
hot: hot
}
}
</script>
我想知道它是否与'async'关键字有关? 当我删除'async'语法并使用promise时。然后它按预期运行并且不删除该行。但是,在这种情况下,它在删除行之前无法执行异步操作。
修改
Handsontable Support在他们的论坛中回答了这个问题:
“钩子当前正在同步运行,只有返回false才能取消动作。
正如我所看到的最后一条评论建议让它工作异步,这是一个好主意。但是,目前,Handsontable仅适用于同步调用,并且不可能只更改一个钩子。“
也就是说,如果有人发现没有挂钩的解决方法以防止基于数据库验证删除行,请分享。
答案 0 :(得分:0)
由于Handsontable是同步的,因此我不得不在调用Handsontable之前插入自己的函数。
我正在使用旧的Handsontable RemoveRow插件(已在1.11.0中删除),该插件在每行旁边添加了删除按钮。显然,如果您不使用RemoveRow插件,则外观将不会完全相同,但是也许可以给您一些想法。
最初,插件会在按下按钮后立即调用Handsontable删除该行:
$(div).on('mouseup', function () {
instance.alter("remove_row", row); // <---
});
我将其替换为对自己函数的调用:
$(div).on('mouseup', function () {
requestRemoveRow(instance, row); // <---
});
现在在我自己的函数中,我可以使用回调发出AJAX请求。如果成功,我将继续进行通常的Handsontable alter
调用以删除该行:
function requestRemoveRow(handsontable, row) {
// Disable remove buttons during request to avoid race condition
$("th.htRemoveRow *").attr("disabled", true);
$.ajax({
url: "resource/" + row,
type: "DELETE"
})
.done(function() {
handsontable.alter("remove_row", row);
})
.always(function() {
// Enable remove buttons after request finishes
$("th.htRemoveRow *").removeAttr("disabled");
})
;
}