gpt4 book ai didi

javascript - 如何阻止模态直到 api 请求得到解决

转载 作者:行者123 更新时间:2023-12-03 00:17:31 26 4
gpt4 key购买 nike

问题

阻止 hideModal() 操作、ESC keydown 处理程序、覆盖单击处理程序直到 EditDepartmentsModal::submitChanges() 的底层 http 的最佳方法是什么请求已解决?

更新

我认为我能做的是:

  • 拦截api调用,在另一个vuex模块设置PENDING状态
  • 检查 hideModal() 操作中的 PENDING 是否为 true。

这不会耦合 vuex 模块吗?这是个好主意吗?

<小时/>

详细信息

我使用单独的 vuex 模块进行模式可见性控制(如建议的 in the article ):

...
state: { modalVisible: false, },
mutations: {
SET_MODAL_VISIBLE(state) { state.modalVisible = true; },
SET_MODAL_INVISIBLE(state) { state.modalVisible = false; },
},
actions: {
showModal(context) { context.commit('SET_MODAL_VISIBLE'); },
hideModal(context) { context.commit('SET_MODAL_INVISIBLE'); },
}
...

Modal.vue(摘录):

<template>
<div class="ui-modal">
<div v-if="visible" @click="closeOnOverlayClicked && hideModal()">
<div :class="cssContainerClasses" @click.stop>
<slot></slot>
</div>
</div>
</div>
</template>
...
mounted() {
if(this.closeOnEscPressed) this.handleEscPressed();
},
computed: {
...mapState('modal', { visible: state => state.modalVisible, }),
},
methods: {
// handles ESC keydown, overlay click
...mapActions('modal', ['hideModal',]),
// other methods ...
}
...

EditDepartmentsModal.vue 组件嵌入 Modal.vue 并允许触发其 submitChanges()cancel() 方法:

<template>
<modal>
<form>
<!-- ... -->
<div class="modal-actions">
<button @click="submitChanges()">Submit</button>
<button @click="cancel()">Cancel</button>
</div>
</form>
</modal>
</template>

<script>
...
methods: {
submitChanges() {
// DepartmentsHttpService was imported before
let rq = DepartmentsHttpService.saveChanges();
rq.then(r => { this.hideModal(); });
rq.catch(e => { /* show errors, log */ this.hideModal(); });
},
cancel() {
// vuex mapped action
this.hideModal();
}
}
...

</script>

对于 API 调用,我决定利用 ( article ) 服务对象来包装 axios 请求:

// DepartmentsHttpService.js
import {HTTP} from '../http';
export default { saveChanges(params) { return HTTP.post('departments', params); }, };
<小时/>

问题质量免责声明

如果您需要更多我的组件代码,我将更新问题。也许现在还不是很完美,我愿意进行编辑。

最佳答案

如果我正确理解了这个问题,用 Promises 似乎很容易解决

async submitChanges() {
try {
// Store the Promise so that we can wait for it from any point in our component
this.saveChangesPromise = DepartmentsHttpService.saveChanges();
await this.saveChangesPromise;
this.hideModal();
} catch(e) {
/* show errors, log */ this.hideModal();
}
},

async handleEscapePressed() {
// If somebody has decided to save, wait for the save action to be finished before we close
if (this.saveChangesPromise){
await this.saveChangesPromise;
}
this.hideModal();
}

关于javascript - 如何阻止模态直到 api 请求得到解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54481793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com