当前位置:首页 > 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 并跳转到首页。

vue 实现登录

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 并重定向到登录页。

vue 实现登录

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中手动实现弹窗组件,需要创建一个独立的弹窗组件,并通过props控制其显示与隐藏。弹窗组件通常包含遮罩层、内容区域和关闭按钮。 <template>…

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录组…

vue实现弹窗可切换

vue实现弹窗可切换

实现弹窗可切换的 Vue 方案 动态组件切换 通过 Vue 的 <component :is="currentComponent"> 动态加载不同弹窗组件,结合 v-if 控制显示状态。…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store 示…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &…