听起来您希望您的操作在开始时设置(提交)一个标志,然后在结束时清除它。
在 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 状态并使用它来禁用您的按钮,例如
<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>
或者,如果您的操作返回一个承诺(如上),您可以在组件内维护请求的进度。例如,假设您的按钮有
<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
})
}
}