2017-12-18 19 views
1

내 앱에 많은 AJAX 요청이 있으며 응답을 받으면 모든 요청에 ​​대해 로딩 아이콘을 표시하고 제거하고 싶습니다. 이 호출에 axios을 사용하고 있으므로 간단한 플러그인 클래스를 만들고 사용자 정의 axios 인터셉터를 추가했습니다.AJAX 로딩을위한 전역 변수 만들기

const MyGlobalVariables= { 
    install(Vue, options) { 

    Vue.load_mask = true; 

    MyGlobalVariables.getLoadMask = function() { 
     return Vue.load_mask; 
    }, 

    MyGlobalVariables.setLoadMask = function(val) { 
     Vue.load_mask = val; 
    } 

    } 
}; 
export default MyGlobalVariables; 

그런 다음 인터셉터

// Add a request interceptor 
window.axios.interceptors.request.use(function (config) { 

    // Do something before request is sent 
    MyGlobalVariables.setLoadMask(true); 
    console.log(MyGlobalVariables.getLoadMask()); 

    return config; 
}, function (error) { 
    MyGlobalVariables.setLoadMask(false); 

    console.log(MyGlobalVariables.getLoadMask()); 
    // Do something with request error 
    return Promise.reject(error); 
}); 

// Add a response interceptor 
window.axios.interceptors.response.use(function (response) { 

    // control the load mask on AJAX calls 
    MyGlobalVariables.setLoadMask(false); 
    console.log(MyGlobalVariables.getLoadMask()); 
    return response; 

}, function (error) { 

    MyGlobalVariables.setLoadMask(false); 
    console.log(MyGlobalVariables.getLoadMask()); 
    // Do something with response error 
    return Promise.reject(error); 
}); 

그래서 그 부분은 잘 작동합니다. 내 전역 변수는 적절한 시간에 true/false로 토글됩니다. 내가 어려움을 겪고있는 것은 실제로 어떻게 토글하는 메인 템플릿에 변수를 설정합니까?

예를 들어, 내 전체 프로젝트의 루트 인 inline-template이 있습니다. 내 home.js 파일에 다음

<home :user="user" inline-template> 
    // Bunch of content here 

    <div v-if="shouldShowLoadMask" class='lmask'></div> 
</home> 

:

import MyGlobalVariables from "./extras/my-global"; 

Vue.component('home', { 
    props: ['user'], 

    computed: { 
    shouldShowLoadMask() { 
     console.log('show load mask? ' + MyGlobalVariables.getLoadMask()); 
     return MyGlobalVariables.getLoadMask(); 
    }, 
    } 

문제는 응용 프로그램의 시작 부분에 한 번 발사 전용 shouldShowLoadMask입니다. 그래서 나는 watch (또는 비슷한 것)을 플러그인 변수에 필요로한다. 그러나 어떻게? 누군가 Vuex를 참조한 예를 보았지만 앱에서 사용하지 않았습니다.

TL : DR : v-if으로 요소를 전환 할 수 있도록 전역 플러그인 변수를 어떻게 모니터링합니까?

+1

Vuex를 사용하지 않는 것은 부끄러운 일입니다. 내 응용 프로그램에서 상태를 처리하는 데 완벽하다는 것을 알았고 API 호출과 프레젠테이션 구성 요소 사이의 버퍼로 광범위하게 사용합니다. – Phil

+0

Vuex에 대한 리팩터링을 시도해보십시오. 이렇게하면 두통을 줄일 수 있습니다. –

+0

문제는 응용 프로그램이 Vuex를 사용하지 않는 스파크 위에 구축된다는 것입니다. 그리고 모든 것이 끝났습니다. 이것을 제외하고는 모든 것이 제대로 작동합니다. 그게 유일한 방법이라면 다른 해결책을 찾아 보겠습니다. 나는이 작은 물건을 위해 Vuex를 포함하는 것을 싫어한다. – Nathan

답변

0

반응성 글로벌 변수를 만드는 매우 간단한 방법은 Vue를 사용하는 것입니다.

const global = new Vue({data:{loading: false}}) 

const GlobalPlugin = { 
    install(Vue){ 
    Vue.prototype.$global = global 
    } 
} 

는 그런 다음과 같이 뷰에서 사용할 수 있습니다 : 여기 개념이다

console.clear() 
 

 
// set up the reactive global object 
 
const global = new Vue({data:{loading: false}}) 
 

 
// make a plugin to add it to Vue 
 
const GlobalPlugin = { 
 
    install(Vue){ 
 
    Vue.prototype.$global = global 
 
    } 
 
} 
 

 
Vue.use(GlobalPlugin) 
 

 
// Set up a faux change to the global loading property 
 
setInterval(() => global.loading = !global.loading, 2000) 
 

 
// Reactivity! 
 
Vue.component("some-component", { 
 
    template:` 
 
    <div> 
 
     <h2> Some component </h2> 
 
     Loading: {{$global.loading}} 
 
    </div> 
 
    ` 
 
}) 
 

 
new Vue({ 
 
    el: "#app", 
 
    computed:{ 
 
    loading() { 
 
     return this.$global.loading 
 
    } 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script> 
 
<div id="app"> 
 
    <h2>Root Vue</h2> 
 
    Loading: {{loading}} 
 
    <some-component></some-component> 
 
</div>

은 물론 앱에 약간의 작업을 할 필요가 있지만, 이것은이다 의 핵심은 매우입니다.