vue拦截器实现
Vue 拦截器实现方法
Vue 拦截器通常用于在请求或响应被处理前进行统一操作,例如添加认证头、处理错误等。以下是两种常见拦截器的实现方式:
Axios 请求/响应拦截器
安装 Axios(如未安装):

npm install axios
创建拦截器文件(如 http.js):
import axios from 'axios';
// 创建实例
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
// 请求拦截器
instance.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
response => {
return response.data;
},
error => {
if (error.response.status === 401) {
alert('登录过期,请重新登录');
router.push('/login');
}
return Promise.reject(error);
}
);
export default instance;
Vue Router 导航守卫(路由拦截器)
在路由配置文件(如 router/index.js)中添加全局守卫:

import Vue from 'vue';
import Router from 'vue-router';
import store from '../store';
Vue.use(Router);
const router = new Router({
routes: [...]
});
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !store.getters.isLoggedIn) {
next('/login');
} else {
next();
}
});
// 全局后置钩子
router.afterEach((to, from) => {
document.title = to.meta.title || '默认标题';
});
export default router;
自定义拦截器(高阶组件)
对于组件级别的拦截,可使用高阶组件模式:
function withAuthCheck(WrappedComponent) {
return {
mounted() {
if (!this.$store.getters.isLoggedIn) {
this.$router.replace('/login');
}
},
render(h) {
return h(WrappedComponent);
}
};
}
使用方式:
export default withAuthCheck(YourComponent);
注意事项
- 拦截器中的异步操作需返回 Promise 或使用 async/await
- 避免在拦截器中执行耗时操作以免阻塞主流程
- 路由拦截器可通过
to.matched.some(record => record.meta.requiresAuth)检查嵌套路由 - 对于 Axios 拦截器,可通过
config.url实现特定 URL 的过滤处理






