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

时间:2019-02-01 14:47:07

标签: javascript vue.js vuex

问题

hideModal()的基础HTTP请求得到解决之前,我可以阻止EditDepartmentsModal::submitChanges()操作,ESC键按下处理程序,覆盖点击处理程序的最佳方法是什么?

更新

我想我能做的是:

  • 拦截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); }, };

问题质量免责声明

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

1 个答案:

答案 0 :(得分:1)

如果我对问题的理解正确,那么使用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();
}