当前位置:首页 > VUE

vue实现登录判定页面

2026-01-22 08:52:29VUE

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 };
}

在组件中使用:

vue实现登录判定页面

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 状态码:

vue实现登录判定页面

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

标签: 页面vue
分享给朋友:

相关文章

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keyword…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue实现新闻

vue实现新闻

Vue 实现新闻功能 使用 Vue 实现新闻功能通常涉及新闻列表展示、新闻详情页、分类筛选等模块。以下是实现的基本思路和代码示例。 新闻列表展示 通过 Vue 组件展示新闻列表,通常使用 v-for…

vue实现mui

vue实现mui

使用 Vue 实现 MUI(Material-UI)风格的界面 Vue 本身不直接提供 MUI(Material Design)组件,但可以通过集成第三方库或手动实现来达到类似效果。以下是几种常见方法…

vue 实现 confirm

vue 实现 confirm

实现确认对话框的方法 在Vue中实现确认对话框可以通过多种方式完成,包括使用内置组件、第三方库或自定义组件。 使用浏览器原生confirm 最简单的实现方式是直接调用浏览器原生的confirm方法。…

vue实现截屏怎么实现

vue实现截屏怎么实现

Vue实现截屏的方法 使用html2canvas库 html2canvas是一个流行的JavaScript库,可以将网页元素转换为Canvas图像。在Vue项目中安装html2canvas: npm…