我有一个带有两个组件的小沙盒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 Promise的原理,但我仍无法弄清在这种情况下它是如何工作的。它可以完美运行,但是我不喜欢使用我不理解的代码。
在ModalConfirmation
中,对于b-modal
标签,这些是设置模态结果的事件。但是,vuejs / bootstrap-vue如何使它与promise匹配?
@ok="resolvePromise(true)"
@cancel="resolvePromise(false)"
@close="resolvePromise(false)"
因为在显示模态时会调用promise构造函数,仅此而已...
此外,如果我对此发表评论
resolvePromise: null,
rejectPromise: null
在模式组件中,它仍然有效。有人可以在这种情况下向我解释承诺解决的流程吗?
答案 0 :(得分:3)
模板中的data
是Vue组件方法中的this
。
发生了什么事
调用show
时,将与new Promise
和{{同步地调用传递到resolve
的函数( promise执行程序函数) 1}}特定于该承诺的功能:被调用时,它们将解决或拒绝该承诺。 reject
中的promise执行者将它们以show
和resolvePromise
的形式存储在Vue组件数据中:
rejectPromise
this.resolvePromise = resolve;
this.rejectPromise = reject;
返回承诺。
使用那些函数作为单击处理程序来呈现组件:
show
模板中的这些功能与@ok="resolvePromise(true)"
@cancel="resolvePromise(false)"
@close="resolvePromise(false)"
对象上的其他功能一样可用。
data
。您可以在调试器中看到该流(推荐),或者通过添加日志记录语句来查看该流,例如(updated sandbox):
show
您能够注释掉<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
不进行任何更改就是实际上并不需要它们。在一开始就指定它们可以防止数据对象的 shape (它具有的属性和原型)在以后调用resolvePromise: null,
rejectPromise: null
时发生变化,这有助于JavaScript引擎进行优化。但是正如您注意到将其注释掉一样,您没有这样做。