登录和注册

master
guixu0320 1 week ago
parent 47c3182032
commit 423e4e1ec5

@ -14,7 +14,7 @@
"pinia": "2.0.27", "pinia": "2.0.27",
"save": "^2.9.0", "save": "^2.9.0",
"vue": "^3.4.37", "vue": "^3.4.37",
"vue-router": "^4.4.5" "vue-router": "4"
}, },
"devDependencies": { "devDependencies": {
"@vitejs/plugin-vue": "^5.1.2", "@vitejs/plugin-vue": "^5.1.2",

@ -1,114 +1,75 @@
<template> <template>
<div class="body-view"> <div class="login-container">
<el-text class="mx-1">登录</el-text> <h2>登录</h2>
<el-text>登录状态{{loginState}}</el-text> <form @submit.prevent="handleLogin">
<div>
<el-form class="form-view"> <label for="username">用户名</label>
<el-form-item label="账号:"> <input type="text" id="username" v-model="username" required />
<el-input class="ipt" v-model="form.account" placeholder="请输入账号"></el-input> </div>
</el-form-item> <div>
<el-form-item label="密码:" style="margin-bottom: 40px;"> <label for="password">密码</label>
<el-input class="ipt" type="password" v-model="form.password" placeholder="请输入密码"></el-input> <input type="password" id="password" v-model="password" required />
</el-form-item> </div>
<el-form-item class="btn-view"> <button type="submit">登录</button>
<el-button class="btn" type="primary" @click="login"></el-button> </form>
<el-button class="btn cancel-btn" type="primary" @click="register"></el-button> <p>
</el-form-item> 还没有账号<router-link to="/register">点击注册</router-link>
</el-form> </p>
</div> </div>
</template> </template>
<script setup>
import request from '../request';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router';
import { storeToRefs } from 'pinia';
import { userStore } from '../store';
const store = userStore() <script>
const {loginState} = storeToRefs(store) export default {
data() {
const form = reactive({ return {
account: "", username: '',
password: "" password: ''
}) };
const message = ref("") },
const router = useRouter() methods: {
const login = () => { handleLogin() {
console.log(form.account, form.password) const storedUser = JSON.parse(localStorage.getItem(this.username));
if (storedUser && storedUser.password === this.password) {
request({ alert('登录成功!');
url:"http://www.fj84.site/login", // user/index.vue
method:"get", this.$router.push('/user');
params:{ } else {
account:form.account, alert('用户名或密码错误');
password:form.password }
}
}).then(res => {
let myType = "error"
if(res.data.code == 1){
myType = "success"
router.push({
name:"User"
})
store.setLoginState(true)
}else{
myType = "error"
} }
ElMessage({ }
message:res.data.message, };
type:myType
})
}).catch(error => {
console.log(error)
})
}
const register = () =>{
router.push({
name:"Register"
})
}
</script> </script>
<style>
.body-view {
border: 1px solid black;
width: 490px;
height: 425px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.mx-1 {
font-size: 25px;
margin-bottom: 20px;
}
.ipt-1 { <style scoped>
font-size: 18px; .login-container {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
} }
.ipt { h2 {
border: 1px solid black; text-align: center;
height: 50px;
} }
.btn { form div {
height: 40px; margin-bottom: 10px;
width: 90px;
background-color: #0f63ff;
} }
.btn-view { button {
margin-top: 30px; width: 100%;
margin-left: 15px; padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
} }
.cancel-btn { button:hover {
margin-left: 70px !important; background-color: #45a049;
} }
</style> </style>

@ -1,97 +1,88 @@
<template> <template>
<el-form <div class="register-container">
ref="ruleFormRef" <h2>注册</h2>
:model="ruleForm" <form @submit.prevent="handleRegister">
status-icon <div>
:rules="rules" <label for="username">用户名</label>
label-width="120px" <input type="text" id="username" v-model="username" required />
class="demo-ruleForm" </div>
> <div>
<el-form-item label="密码" prop="pass"> <label for="password">密码</label>
<el-input v-model="ruleForm.pass" type="password" autocomplete="off" /> <input type="password" id="password" v-model="password" required />
</el-form-item> </div>
<el-form-item label="确认密码" prop="checkPass"> <div>
<el-input <label for="confirmPassword">确认密码</label>
v-model="ruleForm.checkPass" <input type="password" id="confirmPassword" v-model="confirmPassword" required />
type="password" </div>
autocomplete="off" <button type="submit">注册</button>
/> </form>
</el-form-item> <p>
已有账号<router-link to="/">点击登录</router-link>
</p>
<el-form-item label="账号" prop="account"> </div>
<el-input v-model="ruleForm.account" type="text" autocomplete="off" /> </template>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm(ruleFormRef)"></el-button>
<el-button @click="resetForm(ruleFormRef)"></el-button>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const validatePass = (rule: any, value: any, callback: any) => {
if (value === '') {
callback(new Error('请输入密码'))
} else {
if (ruleForm.checkPass !== '') {
if (!ruleFormRef.value) return
ruleFormRef.value.validateField('checkPass')
}
callback()
}
}
const validatePass2 = (rule: any, value: any, callback: any) => {
if (value === '') {
callback(new Error('请再次输入密码'))
} else if (value !== ruleForm.pass) {
callback(new Error("两次输入不一致!"))
} else {
callback()
}
}
const validateAccount = (rule: any, value: any, callback: any) => { <script>
const alphanumericRegex = /^[a-zA-Z0-9]+$/; export default {
if (value.length < 8 || !alphanumericRegex.test(value)) { data() {
callback(new Error('账号需满足长度8且仅由字母和数字组成')); return {
} else { username: '',
callback(); password: '',
confirmPassword: ''
};
},
methods: {
handleRegister() {
if (this.password !== this.confirmPassword) {
alert('密码不一致,请重新输入');
return;
}
if (localStorage.getItem(this.username)) {
alert('用户名已存在,请选择其他用户名');
return;
}
const newUser = {
username: this.username,
password: this.password
};
localStorage.setItem(this.username, JSON.stringify(newUser));
alert('注册成功!');
this.$router.push('/');
}
} }
};
</script>
<style scoped>
.register-container {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
}
h2 {
text-align: center;
}
form div {
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
} }
</style>
const ruleForm = reactive({
pass: '',
checkPass: '',
account: '',
})
const rules = reactive({
pass: [{ validator: validatePass, trigger: 'blur' }],
checkPass: [{ validator: validatePass2, trigger: 'blur' }],
account: [{ validator: validateAccount, trigger: 'blur' }],
})
const submitForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.validate((valid) => {
if (valid) {
console.log('提交成功!')
} else {
console.log('提交失败!')
}
})
}
const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
}
</script>

@ -16,4 +16,26 @@ app.use(ElementPlus)
const pinia=createPinia() const pinia=createPinia()
app.use(pinia) app.use(pinia)
//挂载整个应用 //挂载整个应用
app.mount('#app') app.mount('#app')
app.post('/View/login', (req, res) => {
const { username, password } = req.body;
// 验证用户名和密码
if (username === 'test' && password === '123456') {
res.json({ success: true });
} else {
res.json({ success: false, message: '用户名或密码错误' });
}
});
app.post('/View/register', (req, res) => {
const { username, email, password } = req.body;
// 进行用户名、邮箱的检查并保存用户
// 这里只是简单的示例,实际需要加密密码并存储到数据库
if (username && email && password) {
res.json({ success: true });
} else {
res.json({ success: false, message: '信息不完整' });
}
});

@ -17,6 +17,11 @@ const router = createRouter({
name: 'Login', name: 'Login',
component: () => import('./View/Login.vue') component: () => import('./View/Login.vue')
}, },
{
path:'/register',
name:'Register',
component:()=>import ('./View/Register.vue')
},
{ {
path: '/user', path: '/user',
name: 'User', name: 'User',
@ -36,30 +41,10 @@ const router = createRouter({
component: () => import('./View/user/ExpressForm.vue'), component: () => import('./View/user/ExpressForm.vue'),
} }
] ]
},
{
path: '/register',
name: 'Register',
component: () => import('./View/Register.vue')
} }
] ]
}) })
router.beforeEach((to,from,next)=>{
const store = userStore()
const {loginState} = storeToRefs(store)
console.log("路由守卫:",loginState.value)
if(to.name == "Login"){
next()
}else{
if(loginState.value){
next()
}else{
next({
name:'Login'
})
}
}
})
export default router export default router

@ -729,7 +729,7 @@ vue-demi@*:
resolved "https://registry.yarnpkg.com/vue-demi/-/vue-demi-0.14.10.tgz#afc78de3d6f9e11bf78c55e8510ee12814522f04" resolved "https://registry.yarnpkg.com/vue-demi/-/vue-demi-0.14.10.tgz#afc78de3d6f9e11bf78c55e8510ee12814522f04"
integrity sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg== integrity sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==
vue-router@^4.4.5: vue-router@4:
version "4.4.5" version "4.4.5"
resolved "https://registry.yarnpkg.com/vue-router/-/vue-router-4.4.5.tgz#bdf535e4cf32414ebdea6b4b403593efdb541388" resolved "https://registry.yarnpkg.com/vue-router/-/vue-router-4.4.5.tgz#bdf535e4cf32414ebdea6b4b403593efdb541388"
integrity sha512-4fKZygS8cH1yCyuabAXGUAsyi1b2/o/OKgu/RUb+znIYOxPRxdkytJEx+0wGcpBE1pX6vUgh5jwWOKRGvuA/7Q== integrity sha512-4fKZygS8cH1yCyuabAXGUAsyi1b2/o/OKgu/RUb+znIYOxPRxdkytJEx+0wGcpBE1pX6vUgh5jwWOKRGvuA/7Q==

Loading…
Cancel
Save