当前位置:首页 > VUE

vue axios实现登录源码

2026-01-21 12:23:28VUE

以下是一个基于Vue.js和Axios实现登录功能的完整示例代码,包含前端和后端交互逻辑:

前端部分(Vue组件)

安装Axios依赖:

vue axios实现登录源码

npm install axios

登录组件(Login.vue):

<template>
  <div class="login-container">
    <form @submit.prevent="handleSubmit">
      <input v-model="form.username" type="text" placeholder="用户名">
      <input v-model="form.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 {
      form: {
        username: '',
        password: ''
      },
      error: ''
    }
  },
  methods: {
    async handleSubmit() {
      try {
        const response = await axios.post('/api/login', this.form);
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      } catch (err) {
        this.error = err.response?.data?.message || '登录失败';
      }
    }
  }
}
</script>

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

后端API示例(Node.js Express)

const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');

const app = express();
app.use(bodyParser.json());

const users = [
  { id: 1, username: 'admin', password: 'admin123' }
];

app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    const token = jwt.sign({ userId: user.id }, 'your-secret-key', { expiresIn: '1h' });
    return res.json({ token });
  }

  res.status(401).json({ message: '无效的用户名或密码' });
});

app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

Axios全局配置

在main.js中添加:

vue axios实现登录源码

import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000';
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

Vue.prototype.$http = axios;

路由守卫

在router/index.js中添加:

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

这个实现包含以下关键点:

  • 前端表单数据绑定和提交处理
  • Axios的POST请求发送
  • JWT令牌的存储和后续请求的自动附加
  • 基本的错误处理
  • 路由守卫保护需要认证的页面

可以根据实际需求调整用户验证逻辑、错误处理方式和UI样式。

标签: 源码vue
分享给朋友:

相关文章

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <templ…

mvvm实现vue

mvvm实现vue

MVVM 模式在 Vue 中的实现 MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 的设计灵感来源于此。以下是 MVVM 在 Vue 中的核心实现方式: 数据绑定(M…

vue 实现协同

vue 实现协同

Vue 实现协同编辑的方案 协同编辑指多个用户同时编辑同一文档并实时同步更改。Vue 结合相关库和技术可轻松实现该功能。 使用 WebSocket 实现实时通信 WebSocket 提供全双工通信,…

vue实现左右拉伸

vue实现左右拉伸

实现左右拉伸布局的方法 使用CSS Flexbox布局 Flexbox可以轻松实现左右拉伸的效果。通过设置display: flex和flex-grow属性,可以让元素填充可用空间。 <div…

vue歌词滚动实现

vue歌词滚动实现

实现 Vue 歌词滚动的核心方法 监听当前播放时间 通过 audio 元素的 timeupdate 事件获取当前播放时间,并与歌词时间戳对比。在 Vue 中使用 @timeupdate 绑定事件:…

vue实现匹配显示

vue实现匹配显示

Vue实现匹配显示的方法 使用v-if或v-show指令 通过条件渲染指令v-if或v-show,可以根据条件匹配显示不同的内容。v-if会完全销毁或重建DOM元素,而v-show仅切换CSS的dis…