期望: 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支持在他们的论坛中回答了这个问题:“钩子当前正在同步运行,只有通过返回false才能取消动作。正如我看到最后的评论建议使其工作异步,这是一个好主意。但是,目前,Handsontable只能在同步调用上工作,而且只能改变一个钩子。“
也就是说,如果有人发现没有挂钩的解决方法以防止基于数据库验证删除行,请分享。
由于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");
})
;
}