当前位置:首页 > VUE

vue连接实现登录功能

2026-02-22 17:12:45VUE

创建登录表单组件

在Vue项目中创建一个登录表单组件,通常命名为Login.vue。该组件包含用户名和密码输入框,以及提交按钮。

<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required>
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required>
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    handleLogin() {
      // 登录逻辑将在这里实现
    }
  }
}
</script>

设置API请求

安装axios用于发送HTTP请求到后端API。

npm install axios

在项目中创建或使用现有的API服务文件,通常命名为api.jsauth.js

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://your-api-url.com/api',
});

export const login = (credentials) => {
  return api.post('/login', credentials);
};

实现登录逻辑

在登录组件的handleLogin方法中调用API服务。

vue连接实现登录功能

import { login } from '@/api/auth';

methods: {
  async handleLogin() {
    try {
      const response = await login({
        username: this.username,
        password: this.password
      });

      // 存储token或其他认证信息
      localStorage.setItem('token', response.data.token);

      // 重定向到主页或其他受保护的路由
      this.$router.push('/dashboard');
    } catch (error) {
      console.error('登录失败:', error);
      // 显示错误信息给用户
    }
  }
}

处理认证状态

创建Vuex store来管理用户认证状态。

// store/auth.js
const state = {
  user: null,
  isAuthenticated: false
};

const mutations = {
  SET_USER(state, user) {
    state.user = user;
    state.isAuthenticated = !!user;
  }
};

const actions = {
  async login({ commit }, credentials) {
    const response = await login(credentials);
    commit('SET_USER', response.data.user);
    localStorage.setItem('token', response.data.token);
    return response.data.user;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

创建路由守卫

设置路由守卫来保护需要认证的路由。

vue连接实现登录功能

// router/index.js
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.auth.isAuthenticated;

  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

添加导航守卫

在main.js或入口文件中添加导航守卫,检查用户是否已认证。

// main.js
import store from './store';

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.getters['auth/isAuthenticated']) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

实现注销功能

添加注销功能,清除用户认证信息。

// store/auth.js
const actions = {
  logout({ commit }) {
    commit('SET_USER', null);
    localStorage.removeItem('token');
  }
};

在组件中调用注销action:

methods: {
  handleLogout() {
    this.$store.dispatch('auth/logout');
    this.$router.push('/login');
  }
}

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

相关文章

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

vue ref实现

vue ref实现

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

vue filter 实现

vue filter 实现

在 Vue.js 中,过滤器(Filter)是一种用于文本格式化的功能,可以在模板中直接使用。以下是实现过滤器的详细方法: 全局过滤器注册 通过 Vue.filter 方法注册全局过滤器,可在所有组…

vue 实现$(id)

vue 实现$(id)

在 Vue 中实现类似 jQuery 的 $(id) 功能,可以通过以下几种方式操作 DOM 元素: 使用 ref 属性 Vue 推荐使用 ref 属性来直接访问 DOM 元素或组件实例。在模板中为…

vue 轮询实现

vue 轮询实现

轮询的基本概念 轮询是一种通过定时向服务器发送请求来获取最新数据的技术。适用于需要实时更新但无法使用WebSocket的场景。 使用setInterval实现轮询 在Vue组件中,可以通过setIn…

vue实现秒表

vue实现秒表

实现秒表功能 在Vue中实现秒表功能需要处理时间显示、开始、暂停和重置逻辑。以下是具体实现方式: 基础实现代码 <template> <div> <div&…