当前位置:首页 > VUE

vue登录功能实现

2026-01-19 08:33:08VUE

Vue 登录功能实现

创建登录表单组件

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

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

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

实现登录逻辑

handleSubmit 方法中调用后端 API 进行验证。使用 axios 发送 POST 请求,传递用户名和密码。

methods: {
  async handleSubmit() {
    try {
      const response = await axios.post('/api/login', {
        username: this.username,
        password: this.password
      })
      // 处理登录成功
    } catch (error) {
      // 处理错误
    }
  }
}

处理登录状态

登录成功后,保存返回的 token 到本地存储或 Vuex 中,并跳转到主页。

vue登录功能实现

localStorage.setItem('token', response.data.token)
this.$router.push('/home')

路由守卫配置

在路由配置中添加全局前置守卫,检查用户是否已登录,未登录则重定向到登录页。

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

错误处理和用户反馈

在登录失败时显示错误信息,增强用户体验。

vue登录功能实现

catch (error) {
  this.errorMessage = '用户名或密码错误'
}

表单验证

添加基本的表单验证,确保用户名和密码不为空。

if (!this.username || !this.password) {
  this.errorMessage = '请输入用户名和密码'
  return
}

样式优化

为登录表单添加 CSS 样式,提升视觉效果。

form {
  display: flex;
  flex-direction: column;
  max-width: 300px;
  margin: 0 auto;
}
input {
  margin-bottom: 10px;
  padding: 8px;
}
button {
  padding: 10px;
  background: #42b983;
  color: white;
  border: none;
}

通过以上步骤可以实现一个完整的 Vue 登录功能,包括表单创建、数据提交、状态管理和路由控制等关键部分。

标签: 功能vue
分享给朋友:

相关文章

vue实现rtc

vue实现rtc

Vue 实现 RTC 的步骤 安装依赖 在 Vue 项目中安装 WebRTC 相关依赖,如 simple-peer 或 peerjs,用于简化 WebRTC 的实现。 运行以下命令安装 simple-…

vue插件实现

vue插件实现

Vue 插件实现方法 Vue 插件是一种向 Vue 应用程序添加全局功能的机制。插件可以包含全局指令、过滤器、混入、实例方法等。 插件的基本结构 一个 Vue 插件通常是一个对象或函数,需要暴露一个…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…

vue实现浮标

vue实现浮标

Vue 实现浮动按钮(浮标) 使用 Vue 实现浮动按钮可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 定位和 Vue 组件 创建 Vue 组件并配合 CSS 固定定位实现浮动按钮:…

vue实现treetable

vue实现treetable

Vue实现TreeTable的方法 使用第三方组件库(如Element UI) Element UI的el-table组件支持树形表格展示,通过设置row-key和tree-props属性即可实现。…

vue 实现table

vue 实现table

Vue 实现 Table 的方法 使用原生 HTML 表格 通过 Vue 的 v-for 指令动态渲染表格数据,适合简单表格场景。 <template> <table>…