当前位置:首页 > VUE

使用vue实现登录功能

2026-02-23 16:25:09VUE

创建Vue项目

使用Vue CLI初始化项目:

vue create vue-login-demo

选择默认配置或手动配置(如Router、Vuex等)。

安装依赖

如需使用Axios发送请求:

npm install axios

设计登录表单组件

src/components/Login.vue中创建表单:

<template>
  <div class="login">
    <h3>登录</h3>
    <form @submit.prevent="handleSubmit">
      <input v-model="username" type="text" 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 handleSubmit() {
      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>
.error { color: red; }
</style>

配置路由

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

使用vue实现登录功能

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

Vue.use(Router);

export default new Router({
  routes: [
    { path: '/login', component: Login },
    { path: '/dashboard', component: () => import('../components/Dashboard.vue'), meta: { requiresAuth: true } }
  ]
});

添加路由守卫

src/router/index.js中补充全局前置守卫:

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

后端接口示例(可选)

使用Node.js模拟登录接口:

const express = require('express');
const app = express();
app.use(express.json());

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

app.listen(3000, () => console.log('Server running on port 3000'));

集成Axios

src/main.js中配置Axios全局实例:

使用vue实现登录功能

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';
Vue.prototype.$axios = axios;

状态管理(可选)

如需使用Vuex管理登录状态:

// src/store/index.js
export default new Vuex.Store({
  state: {
    isAuthenticated: false,
    user: null
  },
  mutations: {
    loginSuccess(state, user) {
      state.isAuthenticated = true;
      state.user = user;
    },
    logout(state) {
      state.isAuthenticated = false;
      state.user = null;
    }
  }
});

表单验证增强

使用Vuelidate进行客户端验证:

npm install vuelidate

在组件中引入:

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

export default {
  data() { /* ... */ },
  validations: {
    username: { required },
    password: { required, minLength: minLength(6) }
  },
  methods: {
    handleSubmit() {
      this.$v.$touch();
      if (this.$v.$invalid) return;
      // 提交逻辑
    }
  }
};

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

相关文章

vue实现用户信息删除

vue实现用户信息删除

Vue 实现用户信息删除功能 在 Vue 中实现用户信息删除功能通常涉及前端界面交互和后端 API 调用。以下是实现步骤: 前端界面设计 创建删除按钮或操作项,通常使用 @click 事件触发删除操…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue 实现注册

vue 实现注册

Vue 实现注册功能 注册功能通常包括表单验证、数据提交和用户反馈。以下是实现注册功能的步骤: 1. 创建注册表单组件 在 Vue 项目中创建一个注册表单组件,包含用户名、邮箱、密码等输入字段。…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue实现ios

vue实现ios

Vue 实现 iOS 风格应用 使用 Vue 实现 iOS 风格的应用,可以通过结合 UI 框架和自定义样式来达成目标。以下是具体方法和步骤: 选择 iOS 风格的 UI 框架 Vue 生态中有多…

vue实现双向

vue实现双向

Vue 实现双向绑定的方法 Vue 的双向绑定主要通过 v-model 指令实现,它结合了数据绑定和事件监听,适用于表单元素(如 input、select、textarea 等)。以下是几种常见的实现…