Fab*_*ner 7 vue.js vue-router axios vuejs2
我用 vue-cli 3 创建了一个项目,所以我运行:
>vue create my-app;
>cd my-app
>vue add axios
Run Code Online (Sandbox Code Playgroud)
vue 在 my-app\src\plugins\ 中使用以下代码创建文件 axios.js:
"use strict";
import Vue from 'vue';
import axios from "axios";
// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let config = {
// baseURL: process.env.baseURL || process.env.apiUrl || ""
// timeout: 60 * 1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};
const _axios = axios.create(config);
_axios.interceptors.request.use(
function(config) {
// Do something before request is sent
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
// Add a response interceptor
_axios.interceptors.response.use(
function(response) {
// Do something with response data
return response;
},
function(error) {
// Do something with response error
return Promise.reject(error);
}
);
Plugin.install = function(Vue, options) {
Vue.axios = _axios;
window.axios = _axios;
Object.defineProperties(Vue.prototype, {
axios: {
get() {
return _axios;
}
},
$axios: {
get() {
return _axios;
}
},
});
};
Vue.use(Plugin)
export default Plugin;
Run Code Online (Sandbox Code Playgroud)
但我需要响应拦截器访问 vue-router,我已经尝试从 'vue-router' 添加导入路由器;并使用 Roter.push() 但在执行时说 push 不是一种方法。我也不能使用 This 或 Vue.$router ..
我怎样才能解决这个问题?tks
为了在 axios 拦截器内或几乎在组件文件外的任何地方使用路由器,我们必须导入我们应用程序的路由器实例,该实例是在路由器入口文件中创建的(默认情况下router.js)。
实例应该从相同的路径导入,因为它是在应用程序的入口文件中完成的(默认情况下main.js):
import router from './router'
Run Code Online (Sandbox Code Playgroud)
这样就可以访问所有方法,如文档中所述
| 归档时间: |
|
| 查看次数: |
6674 次 |
| 最近记录: |