当前位置:首页 > VUE

vue的简单登录实现

2026-02-23 03:52:29VUE

创建Vue项目

使用Vue CLI创建一个新项目:

vue create vue-login-demo
cd vue-login-demo

安装必要依赖

安装Vue Router和Axios用于路由和HTTP请求:

npm install vue-router axios

配置路由

src/router/index.js中设置登录路由:

import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

创建登录组件

src/views/Login.vue中实现登录表单:

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

<script>
import axios from 'axios'

export default {
  data() {
    return {
      username: '',
      password: '',
      error: ''
    }
  },
  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('/dashboard')
      } catch (err) {
        this.error = '登录失败,请检查用户名和密码'
      }
    }
  }
}
</script>

<style scoped>
.login {
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
}
.error {
  color: red;
}
</style>

模拟API请求

public/api/login目录下创建模拟响应文件(仅用于开发测试):

{
  "token": "mock-jwt-token"
}

配置Axios基础URL

src/main.js中配置Axios:

import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:8080'

添加路由守卫

src/router/index.js中添加导航守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.name !== 'Login' && !isAuthenticated) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

运行项目

启动开发服务器:

vue的简单登录实现

npm run serve

通过浏览器访问http://localhost:8080/login即可测试登录功能。实际项目中需替换模拟API为真实后端接口,并添加表单验证等增强功能。

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

相关文章

vue实现多层评论回复

vue实现多层评论回复

Vue 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '父…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template>…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,使…

vue实现datalist

vue实现datalist

使用 Vue 实现 HTML5 的 datalist 功能 HTML5 的 <datalist> 元素提供了一种自动完成输入框的功能,允许用户在输入时从预定义的选项列表中选择。以下是几种在…

vue ref实现

vue ref实现

Vue 中 ref 的实现 在 Vue 中,ref 是一个用于创建响应式引用的 API,适用于基本类型和对象。以下是 ref 的核心实现原理和使用方法。 基本实现原理 ref 通过 Reactive…