当前位置:首页 > VUE

vue 实现登录

2026-01-07 22:56:10VUE

Vue 实现登录功能

创建登录表单组件

在 Vue 项目中创建一个登录表单组件(如 Login.vue),包含用户名和密码输入框以及提交按钮。使用 v-model 实现双向数据绑定。

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

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

添加表单验证

在提交前验证用户名和密码是否为空,可以使用 Vue 的计算属性或手动验证。

methods: {
  handleLogin() {
    if (!this.username || !this.password) {
      alert('请输入用户名和密码');
      return;
    }
    // 继续登录逻辑
  }
}

发送登录请求

使用 axios 或其他 HTTP 客户端发送登录请求到后端 API。

import axios from 'axios';

methods: {
  async handleLogin() {
    if (!this.username || !this.password) {
      alert('请输入用户名和密码');
      return;
    }

    try {
      const response = await axios.post('/api/login', {
        username: this.username,
        password: this.password
      });
      // 处理登录成功
    } catch (error) {
      alert('登录失败: ' + error.message);
    }
  }
}

处理登录响应

登录成功后保存用户 token 并跳转到首页。

methods: {
  async handleLogin() {
    // ...验证和请求代码

    try {
      const response = await axios.post('/api/login', {
        username: this.username,
        password: this.password
      });
      localStorage.setItem('token', response.data.token);
      this.$router.push('/');
    } catch (error) {
      alert('登录失败: ' + error.message);
    }
  }
}

添加路由守卫

在 Vue Router 中添加全局前置守卫,保护需要登录的页面。

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

实现登出功能

添加登出方法,清除本地存储的 token 并重定向到登录页。

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

使用 Vuex 管理状态

对于更复杂的应用,可以使用 Vuex 集中管理登录状态。

// store.js
export default new Vuex.Store({
  state: {
    user: null,
    isAuthenticated: false
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
      state.isAuthenticated = true;
    },
    logout(state) {
      state.user = null;
      state.isAuthenticated = false;
    }
  },
  actions: {
    login({ commit }, credentials) {
      return axios.post('/api/login', credentials)
        .then(response => {
          commit('setUser', response.data.user);
          localStorage.setItem('token', response.data.token);
        });
    },
    logout({ commit }) {
      commit('logout');
      localStorage.removeItem('token');
    }
  }
});

添加加载状态

在登录过程中显示加载状态,提升用户体验。

<template>
  <button @click="handleLogin" :disabled="isLoading">
    {{ isLoading ? '登录中...' : '登录' }}
  </button>
</template>

<script>
export default {
  data() {
    return {
      isLoading: false
    }
  },
  methods: {
    async handleLogin() {
      this.isLoading = true;
      try {
        // 登录逻辑
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

记住登录状态

添加"记住我"功能,使用 localStoragecookie 持久化登录状态。

<template>
  <input type="checkbox" v-model="rememberMe" /> 记住我
</template>

<script>
export default {
  data() {
    return {
      rememberMe: false
    }
  },
  methods: {
    handleLogin() {
      if (this.rememberMe) {
        localStorage.setItem('rememberMe', 'true');
      }
      // 其他登录逻辑
    }
  }
}
</script>

vue 实现登录

标签: vue
分享给朋友:

相关文章

vue实现预览

vue实现预览

Vue实现文件预览的方法 使用Vue实现文件预览功能可以通过多种方式完成,具体取决于文件类型(图片、PDF、视频等)。以下是几种常见文件类型的实现方案。 图片预览 通过<input type…

vue实现静态查询

vue实现静态查询

Vue 实现静态查询 在 Vue 中实现静态查询通常指不依赖后端接口,直接在前端处理数据筛选或搜索功能。以下是几种常见实现方式: 使用计算属性过滤数据 通过计算属性对静态数据进行筛选,适合简单查询…

vue登录逻辑的实现

vue登录逻辑的实现

Vue 登录逻辑实现 前端实现 创建登录组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template&…

拖拽式编程vue实现

拖拽式编程vue实现

拖拽式编程在 Vue 中的实现方法 使用 HTML5 原生拖放 API Vue 可以结合 HTML5 的拖放 API 实现基础拖拽功能。通过 draggable 属性标记可拖拽元素,监听 dragst…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现一个系统

vue实现一个系统

Vue 系统实现步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目: npm init vue@latest my-system 选择需要的配置(Router、Pinia 等)。…