用Vue写一个登陆页面
时间: 2023-10-20 22:07:19 浏览: 110
以下是一个简单的 Vue 登录页面的示例代码,包括 HTML 和 Vue 组件:
HTML 代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px" class="login-form">
<el-form-item label="用户名" prop="username">
<el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="login">登录</el-button>
</el-form-item>
</el-form>
</div>
<!-- import Vue.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
<!-- import Vue-Router.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.2.0/vue-router.min.js"></script>
<!-- import ElementUI.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/index.js"></script>
<!-- import axios.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<!-- import main.js -->
<script src="main.js"></script>
</body>
</html>
```
Vue 组件代码:
```javascript
// main.js
Vue.use(VueRouter);
Vue.use(ElementUI);
const loginForm = {
username: '',
password: ''
};
const loginRules = {
username: [
{ required: true, message: "请输入用户名", trigger: "blur" }
],
password: [
{ required: true, message: "请输入密码", trigger: "blur" }
]
};
const login = {
template: `
<div>
<el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px" class="login-form">
<el-form-item label="用户名" prop="username">
<el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="login">登录</el-button>
</el-form-item>
</el-form>
</div>
`,
data() {
return {
loginForm,
loginRules
};
},
methods: {
login() {
this.$refs.loginForm.validate(valid => {
if (valid) {
axios.post('/login', this.loginForm)
.then(res => {
console.log(res.data);
// 登录成功跳转到首页
this.$router.push('/home');
})
.catch(err => {
console.error(err);
this.$message.error('登录失败,请检查用户名和密码!');
});
} else {
console.log('validate failed');
return false;
}
});
}
}
};
const routes = [
{ path: '/', component: login },
{ path: '/home', component: home }
];
const router = new VueRouter({
routes
});
const app = new Vue({
router
}).$mount("#app");
```
其中,`loginForm` 和 `loginRules` 是登录表单的数据和验证规则,`login` 组件包含了登录表单的 HTML 和相关的 Vue 方法,`routes` 定义了两个路由,一个是登录页,一个是首页。`router` 是 VueRouter 实例。
当用户点击“登录”按钮时,`login` 组件会向服务器发送一个 POST 请求,请求的数据是 `loginForm` 中的用户名和密码。如果验证成功,则跳转到首页;否则,提示用户登录失败。
阅读全文