Ste*_*n-v 3 javascript ajax vue.js vue-component
我目前有VueJS组件,可以像这样对github进行ajax调用:
(子级)组件
Vue.http.get('user/repos').then((response) => {
console.log(response);
}, (response) => {
console.log(response);
});
Run Code Online (Sandbox Code Playgroud)
问题在于,我首先需要获取访问令牌,然后才能进行此Ajax调用。此访问令牌存储在数据库中,因此我的主要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.');
})
}
});
Run Code Online (Sandbox Code Playgroud)
我如何确定在从组件运行ajax调用之前,设置“ Authorization”头的ajax调用已成功?
为其他可能受益的人添加此内容。
从API调用中获取令牌,并将其添加到vuex状态变量中。
使用子组件中的getter作为计算属性来访问相同对象,或者可以将其作为prop或通过事件总线传递给它,但是这两种方法都没有使用vuex强大。
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>
})
}
// ----------------------------------------------
Run Code Online (Sandbox Code Playgroud)Watch需要更改值,我注意到操作中的提交导致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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3786 次 |
| 最近记录: |