当前位置:首页 > VUE

vue项目登录实现

2026-03-09 14:05:15VUE

Vue 项目登录功能实现

准备工作

确保已安装 Vue CLI 和必要的依赖,如 vue-routeraxios。创建项目后,设置路由和状态管理(如 Vuex 或 Pinia)。

登录页面设计

创建登录组件 Login.vue,包含表单元素(用户名、密码输入框和提交按钮)。使用 v-model 绑定表单数据。

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="form.username" placeholder="用户名" />
    <input v-model="form.password" type="password" placeholder="密码" />
    <button type="submit">登录</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleLogin() {
      // 登录逻辑
    }
  }
}
</script>

后端接口调用

使用 axios 发送登录请求到后端 API。处理响应并存储 token。

methods: {
  async handleLogin() {
    try {
      const response = await axios.post('/api/login', this.form);
      localStorage.setItem('token', response.data.token);
      this.$router.push('/dashboard');
    } catch (error) {
      console.error('登录失败:', error);
    }
  }
}

路由守卫

配置全局前置守卫,检查用户是否已认证。未登录用户访问受限路由时重定向到登录页。

// router/index.js
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

状态管理

使用 Vuex 或 Pinia 管理用户状态。创建 auth 模块存储登录状态和用户信息。

// store/auth.js
export default {
  state: {
    user: null,
    isAuthenticated: false
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
      state.isAuthenticated = true;
    },
    logout(state) {
      state.user = null;
      state.isAuthenticated = false;
    }
  }
};

注销功能

清除本地存储的 token 并重置状态。

methods: {
  handleLogout() {
    localStorage.removeItem('token');
    this.$store.commit('logout');
    this.$router.push('/login');
  }
}

错误处理和反馈

添加加载状态和错误提示,提升用户体验。

vue项目登录实现

data() {
  return {
    loading: false,
    error: null
  };
},
methods: {
  async handleLogin() {
    this.loading = true;
    this.error = null;
    try {
      // 登录逻辑
    } catch (error) {
      this.error = '用户名或密码错误';
    } finally {
      this.loading = false;
    }
  }
}

安全性考虑

确保使用 HTTPS 传输数据,后端验证输入并实现 CSRF 保护。前端敏感信息避免硬编码。

标签: 项目vue
分享给朋友:

相关文章

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue实现 toast

vue实现 toast

Vue 实现 Toast 组件 在 Vue 中实现 Toast 组件可以通过多种方式完成,以下是几种常见的方法: 使用全局组件和事件总线 创建一个全局的 Toast 组件,并通过事件总线或 Vue…

vue实现list

vue实现list

Vue 实现列表渲染 在 Vue 中,可以使用 v-for 指令来渲染列表。v-for 指令基于一个数组或对象来渲染一个列表,可以遍历数组或对象的属性。 基本列表渲染 <template>…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…

实现简单vue

实现简单vue

实现一个简单的 Vue.js 框架 Vue.js 的核心功能包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化版的 Vue 实现,涵盖基本功能。 数据响应式系统 使用 Object.define…

vue实现slidedown

vue实现slidedown

Vue 实现 SlideDown 动画效果 在 Vue 中实现 SlideDown 效果可以通过 CSS 过渡或动画结合 Vue 的过渡系统完成。以下是几种常见方法: 使用 Vue Transiti…