当前位置:首页 > VUE

如何基于vue实现登录

2026-01-20 22:56:54VUE

创建Vue项目

使用Vue CLI初始化项目:

vue create vue-login-demo
cd vue-login-demo
npm install axios vue-router

配置路由

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

如何基于vue实现登录

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-container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <input v-model="form.username" placeholder="用户名" type="text" required />
      <input v-model="form.password" placeholder="密码" type="password" required />
      <button type="submit">登录</button>
    </form>
  </div>
</template>

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

export default {
  setup() {
    const form = ref({
      username: '',
      password: ''
    })
    const router = useRouter()

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

    return { form, handleLogin }
  }
}
</script>

配置API请求

src/main.js中设置axios全局配置:

如何基于vue实现登录

import axios from 'axios'
axios.defaults.baseURL = 'http://your-api-domain.com'

添加路由守卫

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

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

样式优化

src/views/Login.vue中添加基础样式:

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
input {
  display: block;
  width: 100%;
  margin: 10px 0;
  padding: 8px;
}
button {
  width: 100%;
  padding: 10px;
  background: #42b983;
  color: white;
  border: none;
}
</style>

标签: vue
分享给朋友:

相关文章

vue实现横向导航

vue实现横向导航

vue实现横向导航的方法 使用Flex布局实现横向导航 在Vue中可以通过Flex布局快速实现横向导航。创建一个组件,使用display: flex和flex-direction: row属性使导航项…

vue中实现显示和隐藏

vue中实现显示和隐藏

控制显示与隐藏的方法 在Vue中实现元素的显示和隐藏可以通过多种方式完成,以下是常见的几种方法: 1. 使用v-if指令v-if根据条件动态添加或移除DOM元素,适合需要频繁切换的场景。当条件为fa…

vue实现a

vue实现a

Vue 实现 A 功能的方法 在 Vue 中实现 A 功能可以通过多种方式,具体取决于 A 功能的具体需求。以下是几种常见的实现方法: 使用 Vue 组件 通过创建自定义组件来实现 A 功能。组件可…

vue原理实现

vue原理实现

Vue 原理实现的核心机制 Vue.js 的核心原理基于响应式系统、虚拟 DOM 和模板编译。以下是其核心实现机制的分解: 响应式系统 Vue 使用 Object.defineProperty(Vu…

实现vue框架

实现vue框架

Vue框架的基本实现 Vue是一个渐进式JavaScript框架,用于构建用户界面。以下是实现Vue框架的基本步骤: 安装Vue 通过CDN引入Vue是最简单的方式: <script src…

vue ref实现

vue ref实现

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