当前位置:首页 > VUE

vue3.0登录实现

2026-01-22 14:39:52VUE

Vue 3.0 登录功能实现

准备工作

确保已安装 Vue 3.0 及相关依赖(如 Vue Router、Axios)。通过以下命令创建项目:

npm init vue@latest

创建登录组件

src/components 目录下创建 Login.vue 文件,包含表单和基础逻辑:

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <button type="submit">登录</button>
  </form>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const username = ref('');
const password = ref('');
const router = useRouter();

const handleLogin = async () => {
  try {
    const response = await axios.post('/api/login', {
      username: username.value,
      password: password.value
    });
    localStorage.setItem('token', response.data.token);
    router.push('/dashboard');
  } catch (error) {
    alert('登录失败');
  }
};
</script>

配置路由

src/router/index.js 中设置登录路由和权限控制:

import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import Dashboard from '../components/Dashboard.vue';

const routes = [
  { path: '/login', component: Login },
  { 
    path: '/dashboard', 
    component: Dashboard,
    meta: { requiresAuth: true }
  }
];

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

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

export default router;

后端接口对接

使用 Axios 拦截器添加 token 到请求头:

// src/main.js 或单独封装 axios
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

状态管理(可选)

如需全局管理用户状态,可使用 Pinia:

// stores/auth.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    isAuthenticated: !!localStorage.getItem('token')
  }),
  actions: {
    login(userData) {
      this.user = userData;
      this.isAuthenticated = true;
    }
  }
});

表单验证(可选)

添加基础验证逻辑:

const validateForm = () => {
  if (!username.value || !password.value) {
    alert('请填写完整信息');
    return false;
  }
  return true;
};

// 在 handleLogin 中调用
if (!validateForm()) return;

响应式样式

为登录表单添加基础样式:

vue3.0登录实现

<style scoped>
form {
  display: flex;
  flex-direction: column;
  max-width: 300px;
  margin: 0 auto;
}
input {
  margin-bottom: 10px;
  padding: 8px;
}
</style>

分享给朋友:

相关文章

vue表格实现复选框

vue表格实现复选框

vue表格实现复选框 在Vue中实现表格复选框功能,可以通过以下方法完成: 方法一:使用el-table(Element UI) 安装Element UI后,在表格列中直接添加type="sele…

vue原型实现

vue原型实现

Vue 原型实现的关键点 Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。 数据响应式原理 Vue 通过 Objec…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue实现购票

vue实现购票

Vue 实现购票功能 数据结构设计 购票功能通常需要以下数据结构: 场次信息(时间、地点、价格) 座位信息(可选座位、已售座位) 用户订单信息 示例数据结构: data() { return…

vue 实现拖拉

vue 实现拖拉

Vue 实现拖拽功能的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…