当前位置:首页 > VUE

vue实现简单登陆

2026-02-24 21:27:17VUE

创建Vue项目

使用Vue CLI快速初始化项目:

npm install -g @vue/cli
vue create vue-login-demo
cd vue-login-demo
npm run serve

设计登录表单

src/components/Login.vue 中编写表单:

vue实现简单登陆

<template>
  <div class="login">
    <h3>用户登录</h3>
    <form @submit.prevent="handleSubmit">
      <input v-model="username" type="text" placeholder="用户名" required />
      <input v-model="password" type="password" placeholder="密码" required />
      <button type="submit">登录</button>
    </form>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

实现数据绑定与逻辑

在同一个文件中添加脚本部分:

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      error: ''
    }
  },
  methods: {
    handleSubmit() {
      if (this.username === 'admin' && this.password === '123456') {
        alert('登录成功');
        this.$router.push('/dashboard'); // 假设有路由配置
      } else {
        this.error = '用户名或密码错误';
      }
    }
  }
}
</script>

添加样式

<style> 标签中补充基础样式:

vue实现简单登陆

.login {
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
input {
  display: block;
  width: 100%;
  margin: 10px 0;
  padding: 8px;
}
button {
  width: 100%;
  padding: 8px;
  background: #42b983;
  color: white;
  border: none;
}
.error {
  color: red;
}

配置路由(可选)

若需跳转,在 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: '/', component: Login },
    { path: '/dashboard', component: Dashboard }
  ]
})

运行与测试

启动开发服务器后访问 http://localhost:8080,测试以下场景:

  • 输入正确凭证(admin/123456)触发跳转或提示
  • 输入错误凭证显示错误信息
  • 空表单提交触发浏览器默认验证提示

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

相关文章

vue实现过程

vue实现过程

Vue 的实现过程 Vue 的实现过程可以分为多个核心模块,包括响应式系统、虚拟 DOM、模板编译等。以下是 Vue 的主要实现过程分析。 响应式系统 Vue 的响应式系统基于 Object.de…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 sl…

vue实现滑块

vue实现滑块

Vue 实现滑块组件的方法 使用原生 HTML 和 Vue 指令 通过 Vue 的 v-model 和事件监听实现基础滑块功能。创建一个包含 input 元素的组件,类型设置为 range,并绑定到…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue实现逻辑

vue实现逻辑

Vue 实现逻辑的核心概念 Vue.js 是一个渐进式 JavaScript 框架,其核心逻辑围绕数据驱动和组件化开发。通过响应式系统、虚拟 DOM 和组件生命周期等机制,Vue 实现了高效的前端开发…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,…