반응형
Ajax 요청 중에 Vue.js가 구성 요소를 사용하지 않도록 설정함
다음 문제에 대한 간단한 해결책을 찾고 있습니다.
Ajax 요청을 할 수 있는 Vue 컴포넌트 버튼이 있습니다.요청이 보류 중일 때(복수의 요청을 방지하기 위해) 이 버튼을 해제하고 싶습니다.
플래그가 시작될 때 플래그를 설정하고(커밋) 종료될 때 플래그를 지우는 작업을 원하는 것 같습니다.
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')
})
}
}
이제 컴포넌트 내에서loadingstate 및 그것을 사용하여 버튼을 비활성화합니다.
<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
})
}
}
State.js:
state: {
pendingRequest: false
},
actions: {
fetchRequest: async function(context) {
context.state.pendingRequest = true
let req = await fetch(url)
let data = await req.json()
context.state.pendingRequest = false
}
}
요소.vue:
<button :disabled='$store.state.pendingRequest' @click="$store.dispatch('fetchRequest')">Button</button>
다른 해결책을 찾았습니다.등록된 엔드포인트에 대한 vuex 모듈을 자동으로 생성하고 Axios 인터셉터를 통해 해당 엔드포인트를 감시하고 관련 요청의 상태에 따라 적절한 '보류 중' 상태 값을 설정합니다.
https://github.com/pharkasbence/pending-request-tracker
언급URL : https://stackoverflow.com/questions/51967632/vue-js-disable-component-during-ajax-request
반응형
'programing' 카테고리의 다른 글
| vue-class-component의 유형에 속성이 없습니다. (0) | 2022.07.27 |
|---|---|
| Vue에서 조건에 따라 확인란을 취소하려면 어떻게 해야 합니까? (0) | 2022.07.27 |
| C# Java HashMap 등가물 (0) | 2022.07.27 |
| vue: 내부 컴포넌트에 커스텀 속성을 추가하여 "_ob__" 및 getter/setter를 추가하지 않도록 합니다. (0) | 2022.07.27 |
| 현재 실행 중인 메서드의 이름을 가져오는 중 (0) | 2022.07.27 |