Vue.js 在 ajax 请求期间禁用组件 [英] Vue.js disable component during ajax request
问题描述
我正在为以下问题寻找简单的解决方案:
I'm looking for a simple solution for the following problem:
我有一个 Vue 组件按钮,我可以用它来发出 ajax 请求.我想在请求挂起时禁用此按钮(以防止多个请求).
I have a Vue component button with which I can make an ajax request. I would like to disable this button while the request is pending (to prevent multiple requests).
推荐答案
听起来您希望您的操作在开始时设置(提交)一个标志,然后在结束时清除它.
Sounds like you want your action to set (commit) a flag when it starts and then clear it when it ends.
在 Vuex 中尝试这样的事情...
Try something like this in 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')
})
}
}
现在在您的组件中,您可以映射 loading
状态并使用它来禁用您的按钮,例如
Now in your component, you can map the loading
state and use it to disable your button, eg
<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>
<小时>
或者,如果您的操作返回承诺(如上所述),您可以在组件内维护请求的进度.例如,假设您的按钮具有
Alternatively, you can maintain the progress of the request within your component if your action returns a promise (as above). For example, say your button has
<button :disabled="loading" @click="doTheThing">Do the thing!</button>
和
data () {
return { loading: false }
},
methods: {
doTheThing() {
this.loading = true
this.$store.dispatch('someAjaxActionThatReturnsAPromise').finally(() => {
this.loading = false
})
}
}
这篇关于Vue.js 在 ajax 请求期间禁用组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!