vue怎么实现拦截
Vue 实现拦截的方法
在 Vue 中实现拦截通常涉及以下几种场景:路由拦截、HTTP 请求拦截、全局状态拦截等。以下是具体的实现方法。
路由拦截(导航守卫)
Vue Router 提供了导航守卫功能,可以在路由跳转前、跳转后或跳转过程中进行拦截处理。
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// 检查是否需要登录
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated()) {
next({ path: '/login' })
} else {
next()
}
} else {
next()
}
})
HTTP 请求拦截(Axios)
使用 Axios 拦截器可以在请求发送前或响应返回后进行拦截处理。

import axios from 'axios'
// 请求拦截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
axios.interceptors.response.use(
response => {
return response
},
error => {
if (error.response.status === 401) {
// 跳转到登录页
window.location.href = '/login'
}
return Promise.reject(error)
}
)
全局状态拦截(Vuex)
通过 Vuex 的插件或中间件机制,可以在状态变更前后进行拦截处理。
const store = new Vuex.Store({
state: { ... },
mutations: { ... },
plugins: [
store => {
store.subscribe((mutation, state) => {
// 拦截状态变更
if (mutation.type === 'SOME_MUTATION') {
console.log('状态已变更:', mutation.payload)
}
})
}
]
})
组件生命周期拦截
在组件生命周期钩子中可以进行拦截处理,例如在 beforeCreate 或 beforeMount 时检查权限。

export default {
beforeCreate() {
if (!isAuthenticated()) {
this.$router.push('/login')
}
}
}
自定义指令拦截
通过自定义指令可以在 DOM 元素上实现拦截逻辑。
Vue.directive('permission', {
inserted(el, binding) {
const { value } = binding
if (!hasPermission(value)) {
el.parentNode.removeChild(el)
}
}
})
使用方法:
<button v-permission="'admin'">仅管理员可见</button>
以上方法涵盖了 Vue 中常见的拦截场景,可以根据实际需求选择合适的方式。






