我有一个带有两个组件的小沙盒here。对象列表(示例为“组”)和确认模式。单击删除按钮时将触发模态。 (此沙箱是从another post中提取的,我在其中询问了将模态结果发送到父组件GroupList
的不同方法)。
这里是模式部分:
<template>
<b-modal
id="modalConfirmation"
title="Confirmation"
ok-variant="danger"
@cancel="resolvePromise(false)"
@ok="resolvePromise(true)"
@close="resolvePromise(false)"
>Are you sure you want to delete this row ?</b-modal>
</template>
<script>
export default {
name: "ModalConfirmation",
data() {
return {
group: null,
resolvePromise: null,
rejectPromise: null
};
},
methods: {
show(group) {
return new Promise((resolve, reject) => {
this.group = group;
this.$bvModal.show("modalConfirmation");
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
}
}
};
</script>
对我来说最好的解决方案就是这个。但是,虽然我了解JavaScript承诺的原理,但是我无法弄清楚在这种情况下它是如何工作的。它可以完美运行,但是我不喜欢使用我不理解的代码。
在ModalConfirmation
中,对于b-modal
标记,这些是设置模态结果的事件。但是,vuejs / bootstrap-vue如何使它与promise匹配?
@ok="resolvePromise(true)"
@cancel="resolvePromise(false)"
@close="resolvePromise(false)"
因为在显示模态时将调用promise构造函数,仅此而已...
此外,如果我对此发表评论
resolvePromise: null,
rejectPromise: null
在模态组件中,它仍然有效。有人可以在这种情况下向我解释承诺解决流程吗?
模板中的data
是Vue组件方法中的this
。
发生的事情:
调用show
时,传递给new Promise
的函数(promise executor函数)与特定于该Promise的resolve
和reject
函数同步调用:调用时,它们将解决或拒绝承诺。 show
中的Promise执行程序将它们作为resolvePromise
和rejectPromise
存储在Vue组件数据中:
this.resolvePromise = resolve;
this.rejectPromise = reject;
[show
返回承诺。
渲染组件,使用那些函数作为单击处理程序:
@ok="resolvePromise(true)"
@cancel="resolvePromise(false)"
@close="resolvePromise(false)"
这些功能与data
对象上的其他功能一样,在模板中可用。
show
。您可以在调试器中看到该流(推荐),或者通过添加日志记录语句来查看,例如(updated sandbox):
<template>
<b-modal
id="modalConfirmation"
title="Confirmation"
ok-variant="danger"
@cancel="resolvePromise(false)"
@ok="resolvePromise(true)"
@close="resolvePromise(false)"
>Are you sure you want to delete this row ?</b-modal>
</template>
<script>
export default {
name: "ModalConfirmation",
data() {
// *** Added log
console.log("Making data");
return {
group: null,
resolvePromise: null,
rejectPromise: null
};
},
methods: {
show(group) {
// *** Added log
console.log("`show` called");
return new Promise((resolve, reject) => {
this.group = group;
this.$bvModal.show("modalConfirmation");
// *** Wrapped call to `resolve` with a function doing a log statement
this.resolvePromise = flag => {
console.log(`Calling resolve(${flag})`);
resolve(flag);
};
// *** Wrapped call to `reject` with a function doing a log statement
this.rejectPromise = error => {
console.log(`Calling reject(${error})`);
reject(error);
};
});
}
}
};
</script>
您能够注释掉data
的这一部分的原因
resolvePromise: null,
rejectPromise: null
无需进行任何更改,就表示它们实际上不是必需的。在一开始就指定它们可以防止稍后调用show
时更改数据对象的shape(其属性和原型),这有助于JavaScript引擎进行优化。但是,正如您注意到将其注释掉一样,您不必have那样做。