Vue.js在ajax请求期间禁用组件

pha*_*nce 3 vue.js vue-component vuex

我正在寻找以下问题的简单解决方案:

我有一个Vue组件按钮,我可以使用它来发出ajax请求.我想在请求挂起时禁用此按钮(以防止多个请求).

Phi*_*hil 6

听起来你希望你的动作在它启动时设置(提交)一个标志,然后在它结束时清除它.

在Vuex尝试类似的东西......

state: {
  loading: false
},
mutations: {
  isLoading (state) {
    state.loading = true
  },
  doneLoading (state) {
    state.loading = false
  }
},
actions: {
  doAjaxRequest ({ commit }) {
    commit('isLoading')
    return doSomeAjaxRequest().then(res => {
      // success
    }).catch(err => {
      // oh noes
    }).finally(() => {
      commit('doneLoading')
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的组件中,您可以映射loading状态并使用它来禁用您的按钮,例如

<template>
  <button :disabled="loading" @click="doAjaxRequest">Do AJAX!</button>
</template>
<script>
  import { mapState, mapActions } from 'vuex'
  export default {
    computed: mapState(['loading']),
    methods: mapActions(['doAjaxRequest'])
  }
</script>
Run Code Online (Sandbox Code Playgroud)

或者,如果您的操作返回承诺(如上所述),您可以在组件内维护请求的进度.例如,假设你的按钮有

<button :disabled="loading" @click="doTheThing">Do the thing!</button>
Run Code Online (Sandbox Code Playgroud)

data () {
  return { loading: false }
},
methods: {
  doTheThing() {
    this.loading = true
    this.$store.dispatch('someAjaxActionThatReturnsAPromise').finally(() => {
      this.loading = false
    })
  }
}
Run Code Online (Sandbox Code Playgroud)