vue实现登录判定页面
Vue 实现登录判定页面的方法
路由守卫(全局/局部)
在 router/index.js 中配置全局前置守卫,通过 to.meta.requiresAuth 标记需要登录的页面:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token');
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
路由配置示例:
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
组合式API逻辑复用
创建 useAuth.js 组合式函数:
import { ref } from 'vue';
export function useAuth() {
const isLoggedIn = ref(!!localStorage.getItem('token'));
const checkAuth = () => {
if (!isLoggedIn.value) {
router.push('/login');
}
};
return { isLoggedIn, checkAuth };
}
在组件中使用:
import { useAuth } from './useAuth';
const { isLoggedIn, checkAuth } = useAuth();
checkAuth();
状态管理集成(Vuex/Pinia)
Pinia 存储示例(stores/auth.js):
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
token: localStorage.getItem('token') || null
}),
getters: {
isAuthenticated: (state) => !!state.token
}
});
组件中调用:
import { useAuthStore } from '@/stores/auth';
const authStore = useAuthStore();
watchEffect(() => {
if (!authStore.isAuthenticated) {
router.replace('/login');
}
});
后端请求拦截
在 axios 拦截器中处理 401 状态码:
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);
页面级权限控制
在组件 created 钩子中检查:
export default {
created() {
if (!this.$store.getters.isLoggedIn) {
this.$router.push('/login');
}
}
}
动态路由加载
通过后端返回权限数据动态生成路由:
async function initRoutes() {
const userRole = await fetchUserRole();
const routes = filterRoutesByRole(userRole);
router.addRoutes(routes);
}
登录状态持久化
使用 vuex-persistedstate 保持状态:
import createPersistedState from 'vuex-persistedstate';
export default new Vuex.Store({
plugins: [createPersistedState({
key: 'auth',
paths: ['token']
})]
});
注意事项
- 敏感路由应配置服务端验证
- JWT token 需要处理过期逻辑
- 退出登录需清除所有认证信息
- 生产环境应使用
httpOnly的 cookie 存储 token







