当前位置:首页 > 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 };
}

在组件中使用:

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

vue实现登录判定页面

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

相关文章

vue实现tab换行

vue实现tab换行

Vue实现Tab切换的常见方法 使用Vue实现Tab切换功能可以通过多种方式完成,以下是几种常见的方法: 动态组件结合v-if或v-show 通过v-if或v-show控制不同Tab内容的显示…

vue实现后退

vue实现后退

Vue 实现后退功能的方法 在 Vue 中实现后退功能通常可以通过以下几种方式完成,具体取决于应用场景和需求。 使用 window.history API 通过原生 JavaScript 的 win…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axio…

vue实现ssr

vue实现ssr

Vue 实现 SSR(服务端渲染) Vue 的服务端渲染(SSR)允许在服务器端生成完整的 HTML 内容,再发送到客户端,提升首屏加载速度和 SEO 友好性。以下是实现 Vue SSR 的关键步骤和…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户…

vue 实现弹窗

vue 实现弹窗

Vue 实现弹窗的方法 在 Vue 中实现弹窗功能可以通过多种方式完成,以下是几种常见的方法: 使用组件和 v-if/v-show 控制显示 创建一个独立的弹窗组件,通过 v-if 或 v-sho…