给我写一个组件,用vue3+element-puls实现,实现内容为登陆注册切换功能的组件,并且登陆使用用户名密码登陆,注册使用用户名,密码,邮箱祖册,并且使用script setup脚本来写
时间: 2024-10-17 09:10:08 浏览: 51
```html
<template>
<div class="login-register-container">
<el-switch v-model="mode" @change="toggleMode">
<span slot="open">登录</span>
<span slot="close">注册</span>
</el-switch>
<el-form :model="currentForm" ref="form" :inline="true" :rules="formRules" v-if="mode === 'login'">
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="用户名">
<el-input v-model="currentForm.username" placeholder="请输入用户名"></el-input>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="密码">
<el-input type="password" v-model="currentForm.password" placeholder="请输入密码"></el-input>
</el-form-item>
</el-col>
<el-col :span="8">
<el-button type="primary" @click="handleSubmit('login')">登录</el-button>
</el-col>
</el-row>
</el-form>
<el-form :model="registerForm" ref="registerForm" :inline="true" :rules="registerRules" v-if="mode === 'register'">
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="用户名">
<el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="密码">
<el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="邮箱">
<el-input v-model="registerForm.email" placeholder="请输入邮箱地址"></el-input>
</el-form-item>
</el-col>
</el-row>
<el-button type="primary" @click="handleSubmit('register')">注册</el-button>
</el-form>
</div>
</template>
<script setup lang="ts">
import { defineComponent, ref, watch } from "vue";
import { ElSwitch, ElFormItem, ElInput, ElButton } from "element-plus";
const modes = ['login', 'register'];
const mode = ref(modes[0]);
const currentForm = ref({
username: '',
password: ''
});
const registerForm = ref({
username: '',
password: '',
email: ''
});
const formRules = {
username: [{ required: true, message: '请输入用户名' }],
password: [{ required: true, message: '请输入密码' }]
};
const registerRules = {
...formRules,
email: [{ type: 'email', required: true, message: '请输入有效的邮箱地址' }]
};
function toggleMode(e) {
mode.value = e ? modes[1] : modes[0];
}
async function handleSubmit(field: string) {
if (field === 'login') {
// 模拟登录逻辑,实际应用中应连接到服务器验证
console.log(`正在尝试登录 ${currentForm.value.username}`);
} else if (field === 'register') {
// 模拟注册逻辑,实际应用中应连接到服务器保存用户信息
console.log(`正在尝试注册 ${registerForm.value.username}`);
}
}
</script>
<style scoped>
.login-register-container {
display: flex;
flex-direction: column;
gap: 16px;
}
</style>
```
阅读全文