vue实现登录框
实现登录框的基本结构
在Vue中创建一个登录框,需要使用<template>定义HTML结构,<script>处理逻辑,<style>添加样式。以下是一个基础登录框的模板:
<template>
<div class="login-container">
<form @submit.prevent="handleSubmit">
<h2>用户登录</h2>
<div class="form-group">
<label for="username">用户名</label>
<input
type="text"
id="username"
v-model="username"
placeholder="请输入用户名"
required
/>
</div>
<div class="form-group">
<label for="password">密码</label>
<input
type="password"
id="password"
v-model="password"
placeholder="请输入密码"
required
/>
</div>
<button type="submit">登录</button>
</form>
</div>
</template>
数据绑定与事件处理
在<script>中定义数据模型和提交方法,使用v-model实现双向数据绑定:

<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleSubmit() {
// 这里替换为实际的登录逻辑
console.log('提交数据:', {
username: this.username,
password: this.password
});
// 示例:调用API
// this.$axios.post('/login', {
// username: this.username,
// password: this.password
// })
}
}
}
</script>
样式优化
通过<style>添加基础样式,建议使用scoped避免样式污染:

<style scoped>
.login-container {
max-width: 400px;
margin: 50px auto;
padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
}
button {
width: 100%;
padding: 10px;
background-color: #42b983;
color: white;
border: none;
}
</style>
表单验证增强
添加即时验证功能,使用Vuelidate或原生HTML5验证:
import { required, minLength } from 'vuelidate/lib/validators'
export default {
data() {
return { username: '', password: '' }
},
validations: {
username: { required },
password: { required, minLength: minLength(6) }
},
methods: {
handleSubmit() {
if (this.$v.$invalid) {
alert('请检查表单输入')
return
}
// 提交逻辑
}
}
}
完整组件示例
整合所有部分后的完整组件代码:
<template>
<div class="login-container">
<form @submit.prevent="handleSubmit">
<h2>用户登录</h2>
<div class="form-group">
<label for="username">用户名</label>
<input
type="text"
v-model="username"
@blur="$v.username.$touch()"
:class="{ 'error': $v.username.$error }"
>
<p v-if="$v.username.$error" class="error-message">必须填写用户名</p>
</div>
<div class="form-group">
<label for="password">密码</label>
<input
type="password"
v-model="password"
@blur="$v.password.$touch()"
:class="{ 'error': $v.password.$error }"
>
<p v-if="$v.password.$error" class="error-message">密码至少6位</p>
</div>
<button type="submit" :disabled="$v.$invalid">登录</button>
</form>
</div>
</template>
<script>
import { required, minLength } from 'vuelidate/lib/validators'
export default {
data() {
return {
username: '',
password: ''
}
},
validations: {
username: { required },
password: { required, minLength: minLength(6) }
},
methods: {
handleSubmit() {
// 实际登录逻辑
console.log('登录数据:', this.username, this.password)
}
}
}
</script>
<style scoped>
.error {
border-color: red;
}
.error-message {
color: red;
font-size: 0.8em;
}
</style>






