当前位置:首页 > VUE

vue 实现简单登录

2026-03-09 14:48:38VUE

Vue 实现简单登录功能

1. 创建 Vue 项目 使用 Vue CLI 快速搭建项目框架:

vue create login-demo
cd login-demo
npm install axios vue-router

2. 构建登录组件src/components/Login.vue 中创建登录表单:

<template>
  <div class="login">
    <h3>用户登录</h3>
    <form @submit.prevent="handleLogin">
      <input v-model="username" placeholder="用户名" required>
      <input v-model="password" type="password" placeholder="密码" required>
      <button type="submit">登录</button>
    </form>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      error: ''
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await this.$http.post('/api/login', {
          username: this.username,
          password: this.password
        })
        localStorage.setItem('token', response.data.token)
        this.$router.push('/dashboard')
      } catch (err) {
        this.error = '登录失败,请检查用户名和密码'
      }
    }
  }
}
</script>

3. 配置路由src/router/index.js 中设置路由:

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Dashboard from '../components/Dashboard.vue'

Vue.use(Router)

export default new Router({
  routes: [
    { path: '/login', component: Login },
    { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } }
  ]
})

4. 添加请求拦截器src/main.js 中配置 axios:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

axios.defaults.baseURL = 'http://your-api-domain.com'
Vue.prototype.$http = axios

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

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

5. 创建受保护页面src/components/Dashboard.vue 中:

<template>
  <div>
    <h3>欢迎来到仪表盘</h3>
    <button @click="handleLogout">退出登录</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleLogout() {
      localStorage.removeItem('token')
      this.$router.push('/login')
    }
  }
}
</script>

6. 样式优化src/App.vue 中添加基础样式:

<style>
.login {
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
}
input {
  display: block;
  width: 100%;
  margin: 10px 0;
  padding: 8px;
}
.error {
  color: red;
}
</style>

7. 后端接口示例 Node.js 简单登录验证示例:

app.post('/api/login', (req, res) => {
  const { username, password } = req.body
  if (username === 'admin' && password === '123456') {
    res.json({ token: 'fake-jwt-token' })
  } else {
    res.status(401).send('认证失败')
  }
})

8. 表单验证增强 使用 Vuelidate 进行客户端验证:

npm install vuelidate

在组件中添加:

vue 实现简单登录

import { required, minLength } from 'vuelidate/lib/validators'

export default {
  validations: {
    username: { required },
    password: { required, minLength: minLength(6) }
  },
  methods: {
    handleLogin() {
      this.$v.$touch()
      if (this.$v.$invalid) return
      // 继续登录逻辑
    }
  }
}

以上实现包含前端界面、路由保护、Token 存储和基础验证功能,可根据实际需求扩展更多特性如记住密码、验证码等功能。

标签: 简单vue
分享给朋友:

相关文章

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue滚动实现

vue滚动实现

Vue 滚动实现方法 使用原生滚动 在 Vue 中可以通过 ref 获取 DOM 元素,调用原生滚动方法实现滚动效果。适用于简单场景。 <template> <div ref=…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

vue实现编辑

vue实现编辑

Vue 实现编辑功能 在 Vue 中实现编辑功能通常涉及表单绑定、状态管理和事件处理。以下是一个常见的实现方法: 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定: <i…

vue实现动画

vue实现动画

Vue 实现动画的方法 Vue 提供了多种方式来实现动画效果,包括内置的过渡系统、第三方动画库以及直接操作 CSS 或 JavaScript 动画。 使用 Vue 内置过渡系统 Vue 的 <…

vue实现树

vue实现树

Vue 实现树形结构的方法 使用递归组件实现树形结构 递归组件是Vue中实现树形结构的常见方式。通过组件调用自身,可以轻松构建多层嵌套的树形数据。 <template> <ul…