我正在寻找解决以下问题的简单解决方案:
我有一个 Vue 组件按钮,可以使用它发出 ajax 请求。我想在请求待处理时禁用此按钮(以防止多个请求)。
最佳答案
听起来您希望您的操作在开始时设置(提交)一个标志,然后在结束时清除它。
在 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')
})
}
}
现在在您的组件中,您可以映射加载
状态并使用它来禁用您的按钮,例如
<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>
<小时/>
或者,如果您的操作返回 promise (如上所述),您可以在组件内维护请求的进度。例如,假设您的按钮有
<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 请求期间禁用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58056625/