Files
Vue/test/vue2.html
2025-12-01 10:11:46 +08:00

122 lines
3.1 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Vue 登录作业</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
}
.container {
width: 300px;
margin: auto;
}
input {
width: 100%;
padding: 8px;
margin: 8px 0;
}
button {
width: 100%;
padding: 8px;
margin: 8px 0;
cursor: pointer;
}
h2 {
text-align: center;
}
</style>
</head>
<body>
<div id="app" class="container">
<h2>
{{ isLoggedIn ? ("欢迎回来!已登录账号:" + currentUser) : "请登录" }}
</h2>
<!-- 登录表单 -->
<div v-if="!isLoggedIn">
<input type="text" v-model="studentId" placeholder="请输入账号(学号)">
<input type="password" v-model="password" placeholder="请输入密码">
<button @click="login">登录</button>
</div>
<!-- 登出按钮 -->
<div v-else>
<button @click="logout">登出</button>
</div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
isLoggedIn: false,
studentId: "",
password: "",
currentUser: "" // 保存当前登录用户
};
},
methods: {
async login() {
if (!this.studentId || !this.password) {
alert("请输入账号和密码!");
return;
}
// 本地验证:支持两个测试账户
if (
(this.studentId === "2023001" && this.password === "123456") ||
(this.studentId === "admin" && this.password === "admin")
) {
this.isLoggedIn = true;
this.currentUser = this.studentId;
alert("本地验证成功,已登录!");
return;
}
// 否则再尝试服务器验证
try {
// 用 URLSearchParams 发送表单数据
const params = new URLSearchParams();
params.append("studentId", this.studentId);
params.append("password", this.password);
const response = await axios.post("http://117.72.102.219/login.php", params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
console.log("服务器响应:", response.data);
if (response.data === "success") {
this.isLoggedIn = true;
this.currentUser = this.studentId;
alert("服务器验证成功!");
} else {
alert("账号或密码错误!");
}
} catch (error) {
console.error(error);
alert("登录失败,请检查网络或服务器!");
}
},
logout() {
this.isLoggedIn = false;
this.studentId = "";
this.password = "";
this.currentUser = "";
alert("您已退出登录!");
}
}
}).mount("#app");
</script>
</body>
</html>