vue3实现登陆注册
时间: 2024-01-05 11:20:55 浏览: 82
vue登录注册实例详解
5星 · 资源好评率100%
以下是使用Vue3实现登录注册的示例代码:
```vue
<template>
<div>
<h2>登录</h2>
<form ref="loginForm" @submit.prevent="signIn">
<input type="text" v-model="loginForm.username" placeholder="用户名" />
<input type="password" v-model="loginForm.password" placeholder="密码" />
<button type="submit">登录</button>
</form>
<h2>注册</h2>
<form ref="registerForm" @submit.prevent="signUp">
<input type="text" v-model="registerForm.username" placeholder="用户名" />
<input type="password" v-model="registerForm.password" placeholder="密码" />
<button type="submit">注册</button>
</form>
</div>
</template>
<script>
import { ref } from 'vue';
import axios from 'axios';
export default {
setup() {
const loginForm = ref({
username: '',
password: '',
});
const registerForm = ref({
username: '',
password: '',
});
const signIn = async () => {
await validateForm('loginForm');
// 发送登录请求
axios
.post('http://127.0.0.1:80/api/login', {
username: loginForm.value.username,
password: loginForm.value.password,
})
.then((res) => {
console.log('登录成功', res.data);
})
.catch((error) => {
console.log('登录失败', error);
});
};
const signUp = async () => {
await validateForm('registerForm');
// 发送注册请求
axios
.post('http://127.0.0.1:80/api/register', {
username: registerForm.value.username,
password: registerForm.value.password,
})
.then((res) => {
console.log('注册成功', res.data);
})
.catch((error) => {
console.log('注册失败', error);
});
};
const validateForm = async (formName) => {
const formEl = this.$refs[formName];
if (!formEl) return console.log('表单不存在');
await formEl.validate((valid, fields) => {
if (!valid) {
console.log('表单验证失败', fields);
}
});
};
return {
loginForm,
registerForm,
signIn,
signUp,
};
},
};
</script>
```
阅读全文