当前位置:首页 > VUE

vue 实现简单登陆

2026-01-12 04:07:00VUE

Vue 实现简单登录功能

创建 Vue 项目

使用 Vue CLI 创建一个新项目:

vue create login-demo

选择默认配置或手动配置(推荐包含 Vue Router 和 Vuex)。

项目结构

src/
├── components/
│   └── LoginForm.vue
├── views/
│   ├── Login.vue
│   └── Home.vue
├── router/
│   └── index.js
├── store/
│   └── index.js
└── App.vue

登录表单组件

components/LoginForm.vue 中:

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

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    handleSubmit() {
      this.$emit('login', {
        username: this.username,
        password: this.password
      })
    }
  }
}
</script>

登录页面

views/Login.vue 中:

vue 实现简单登陆

<template>
  <div>
    <h1>登录</h1>
    <LoginForm @login="handleLogin" />
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script>
import LoginForm from '@/components/LoginForm.vue'

export default {
  components: { LoginForm },
  data() {
    return {
      error: null
    }
  },
  methods: {
    handleLogin(credentials) {
      this.$store.dispatch('login', credentials)
        .then(() => {
          this.$router.push('/home')
        })
        .catch(error => {
          this.error = error.message
        })
    }
  }
}
</script>

Vuex 状态管理

store/index.js 中:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isAuthenticated: false,
    user: null
  },
  mutations: {
    SET_AUTH(state, payload) {
      state.isAuthenticated = true
      state.user = payload.user
    }
  },
  actions: {
    login({ commit }, credentials) {
      return new Promise((resolve, reject) => {
        // 模拟 API 调用
        if (credentials.username === 'admin' && credentials.password === '123456') {
          commit('SET_AUTH', { user: credentials.username })
          resolve()
        } else {
          reject(new Error('用户名或密码错误'))
        }
      })
    }
  }
})

路由配置

router/index.js 中:

vue 实现简单登陆

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: Home,
      meta: { requiresAuth: true }
    },
    {
      path: '*',
      redirect: '/login'
    }
  ]
})

路由守卫

main.js 中添加全局前置守卫:

import router from './router'
import store from './store'

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.isAuthenticated) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

主页面

views/Home.vue 中:

<template>
  <div>
    <h1>欢迎, {{ $store.state.user }}</h1>
    <button @click="logout">退出</button>
  </div>
</template>

<script>
export default {
  methods: {
    logout() {
      this.$store.commit('SET_AUTH', { user: null })
      this.$store.state.isAuthenticated = false
      this.$router.push('/login')
    }
  }
}
</script>

样式增强

可以添加基础样式到 App.vue

<style>
.error {
  color: red;
}
input {
  display: block;
  margin: 10px 0;
  padding: 8px;
}
button {
  padding: 8px 16px;
}
</style>

运行项目

npm run serve

访问 http://localhost:8080/login 测试登录功能,使用用户名 admin 和密码 123456 可以成功登录并跳转到主页。

标签: 简单vue
分享给朋友:

相关文章

vue实现单页面

vue实现单页面

Vue 实现单页面应用(SPA) Vue.js 是一个渐进式框架,非常适合构建单页面应用(SPA)。SPA 的核心特点是整个应用只有一个 HTML 页面,通过动态加载内容实现页面切换,无需重新加载整个…

vue实现atm

vue实现atm

Vue实现ATM机模拟功能 使用Vue.js实现ATM机模拟功能需要结合组件化开发、状态管理以及用户交互逻辑。以下是关键实现步骤: 核心组件结构 创建以下Vue组件构建ATM界面: Car…

vue怎么实现页面返回

vue怎么实现页面返回

Vue 实现页面返回的方法 在 Vue 中实现页面返回功能,可以通过以下几种方式完成,具体取决于项目使用的路由模式和技术栈。 使用 Vue Router 的编程式导航 通过 this.$router…

vue实现打字机

vue实现打字机

Vue实现打字机效果 在Vue中实现打字机效果可以通过动态更新文本内容并添加延迟来实现。以下是几种常见的实现方法: 使用setInterval实现 <template> <d…

vue 实现简单登陆

vue 实现简单登陆

以下是一个使用 Vue 3 实现的简单登录功能示例,包含表单验证和基础交互逻辑: 创建 Vue 组件 <template> <div class="login-containe…

vue实现弹窗可切换

vue实现弹窗可切换

实现弹窗可切换的 Vue 方案 动态组件切换 通过 Vue 的 <component :is="currentComponent"> 动态加载不同弹窗组件,结合 v-if 控制显示状态。…