当前位置:首页 > 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 持久化登录状态。

vue 实现登录

<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 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <label…

vue实现增删

vue实现增删

Vue 实现增删功能 在 Vue 中实现增删功能通常涉及数据绑定、事件处理和列表渲染。以下是基于 Vue 2 或 Vue 3 的实现方法: 数据定义 初始化一个数组用于存储列表数据,并在 Vue 实…

vue事件实现

vue事件实现

Vue 事件实现方法 在Vue中,事件处理是通过v-on指令或@简写来实现的。以下是几种常见的事件处理方式: 使用v-on指令绑定事件 <button v-on:click="handleC…

vue实现例子

vue实现例子

以下是一些常见的 Vue 实现例子,涵盖基础功能到进阶应用场景: 基础数据绑定 使用 v-model 实现双向数据绑定: <template> <div> &l…

vue源码实现

vue源码实现

Vue 源码实现解析 Vue.js 的核心实现可以分为响应式系统、虚拟 DOM、模板编译、组件化等几个关键部分。以下是对这些核心机制的详细解析。 响应式系统 Vue 的响应式系统基于 Object.…

vue 实现单点登录

vue 实现单点登录

单点登录(SSO)实现原理 单点登录允许用户通过一次身份验证访问多个系统。核心原理是用户首次登录后,认证中心颁发令牌(如Token),其他系统通过验证令牌实现免登录。 Vue中实现SSO的方案 基于…