2017-01-09 31 views
2

我现在有VueJS组件,使一个AJAX调用Github上,像这样:如何等待来自主的Vue例如Ajax调用?

(儿童)组件

Vue.http.get('user/repos').then((response) => { 
    console.log(response); 
}, (response) => { 
    console.log(response); 
}); 

的问题是,我首先需要获得一个访问令牌,然后才能给这个阿贾克斯呼叫。此访问令牌是存储在数据库中,所以我的主要Vue的组件使得AJAX调用设置一个共同的标题,所有的Ajax调用:

主要Vue的实例

Vue.http.headers.common['Authorization'] = `token ${this.token}`; 

const app = new Vue({ 
    el: '#app', 

    data: { 
     token: '' 
    }, 

    created() { 
     Vue.http.get('/token').then((response) => { 
      this.token = response.data.token; 
     },() => { 
      console.log('failed to retrieve the access token for the logged in user.'); 
     }) 
    } 
}); 

我怎么能肯定之前从我的组件Ajax调用的AJAX调用设置“授权”标头已成功?

+1

设置一个'watch'呢? –

+0

@AmreshVenugopal如此简单。甚至没有想过它。谢谢! –

回答

4

添加此为别人谁可以从中受益。

  1. 从API调用中获取令牌,将其添加到vuex状态变量中。

  2. 使用子组件中的吸气剂作为计算属性访问该组件,或者可以将它作为道具或通过事件总线传递,但两种方式都不如使用vuex那么强大。

  3. watch,在物业,并获得令牌时执行您所需的操作。

    // Add this up in the child component 
    
        computed: { 
        ...mapGetters({ 
         token: <name-of-the-getter> // token becomes the alias for the computed 
        })       // property. 
        }, 
    
        watch: { 
        token() { 
         if(this.token) this.someAPICall()// or some other applicable condition 
        } 
        }, 
    
        methods: { 
        ...mapActions({ 
         someAPICall: <name-of-the-action> 
        }) 
        } 
    
    // ---------------------------------------------- 
    

观看要求值来改变,我已经注意到,犯的诉讼中作出导致watch触发。因此,如果由于某种原因令牌丢失或者过期,您自然无法进行后续请求。

编辑

import store from 'path/to/store' 

axios.interceptors.response.use(function (response) { 
    // extract the token from the response object 
    // save the token to the store for access during subsequent 
    // requests. 
    return response; 
}, function (error) { 
    // Do something with response error 
    return Promise.reject(error); 
}); 

axios.interceptors.request.use(function (config) { 
    // use store getters to access token 
    return config; 
}, function (error) { 
    // Do something with request error 
    return Promise.reject(error); 
}); 
+0

任何想法就做什么时,有很多需要标记的地方?重复所有页面的代码或创建一个路线警卫? –

+0

我用爱可信拦截和存储来处理该情况。你想要一个例子吗? –

+0

我看到你的编辑,最好先用拦截器,非常感谢! –

1

可以替代由自己的函数/ proxyfiy Vue.http.get功能,将请求令牌,然后再去做你的要求,粗略的想法:

!function() 
{ 
    var vue_http_get = Vue.http.get; 
    var token = null; 

    // patching/proxying Vue.http.get function 
    Vue.http.get = function get() { 
    vue_http_get.apply(Vue.http,"path/to/get/token/").then(function(resp){ 
     token = resp; 
     Vue.http.headers.common['Authorization'] = ...; 
     // putting back original Vue.http 
     Vue.http = vue_http_get; 
     return Vue.http.get(arguments[0]); 
    }); 
    }; 
}(); 
相关问题