当前位置:首页 > VUE

vue登录的实现

2026-01-17 03:37:35VUE

实现Vue登录功能

安装必要依赖 确保项目中已安装vue-routeraxios,用于路由管理和HTTP请求。通过npm或yarn安装:

npm install vue-router axios

创建登录组件src/components目录下创建Login.vue文件,包含表单和提交逻辑:

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

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  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 (error) {
        console.error('登录失败:', error)
      }
    }
  }
}
</script>

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

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

Vue.use(Router)

export default new Router({
  routes: [
    { path: '/login', component: Login },
    { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } }
  ]
})

添加路由守卫src/main.js或路由配置文件中添加全局前置守卫:

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

后端API交互 通过axios与后端接口通信,需创建src/api/auth.js封装请求:

import axios from 'axios'

export default {
  login(credentials) {
    return axios.post('/api/login', credentials)
  }
}

样式优化 可添加基础样式增强用户体验:

form {
  max-width: 300px;
  margin: 0 auto;
}
input {
  display: block;
  margin: 10px 0;
  width: 100%;
}

表单验证 使用vee-validate或手动验证增强安全性:

vue登录的实现

methods: {
  validateForm() {
    return this.username.length > 0 && this.password.length >= 6
  }
}

标签: vue
分享给朋友:

相关文章

vue实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdown…

vue实现动画

vue实现动画

Vue 实现动画的方法 Vue 提供了多种方式来实现动画效果,包括内置的过渡系统、第三方动画库以及直接操作 CSS 或 JavaScript 动画。 使用 Vue 内置过渡系统 Vue 的 <…

vue实现gps

vue实现gps

Vue 中实现 GPS 定位功能 在 Vue 中实现 GPS 定位功能通常依赖于浏览器的 Geolocation API 或第三方地图服务(如高德、百度地图等)。以下是两种常见的实现方式: 使用浏览…

vue 实现分屏

vue 实现分屏

Vue 实现分屏的方法 使用 CSS Flexbox 或 Grid 布局 通过 CSS Flexbox 或 Grid 布局可以轻松实现分屏效果。在 Vue 组件中定义两个或多个区域,并使用 CSS 控…

vue 简单实现

vue 简单实现

以下是 Vue 的简单实现示例,涵盖基础模板、数据绑定、方法及生命周期: 基础模板与数据绑定 <div id="app"> <p>{{ message }}</p&…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能可以通过多种方式完成,以下是几种常见的方法: 使用数组模拟队列 队列遵循先进先出(FIFO)原则,可以用数组的 push 和 shift 方法模拟入队…