20230725----重返学习-vue3项目实战-知乎日报第2天
发布人:shili8
发布时间:2025-03-01 15:59
阅读次数:0
**重返学习——Vue3项目实战——知乎日报第2天**
今天是我们学习Vue3的第二天,我们将继续完善我们的知乎日报项目。昨天我们完成了基本的页面布局和数据展示,今天我们将重点关注用户登录和注册功能。
### 登录和注册功能在知乎日报中,用户需要登录才能发布自己的文章。因此,我们需要实现一个登录和注册功能。
#### 登录功能首先,我们需要创建一个登录组件。新建一个文件`Login.vue`:
html<template> <div class="login-container"> <h1>登录</h1> <form @submit.prevent="handleLogin"> <input type="text" v-model="username" placeholder="用户名"> <input type="password" v-model="password" placeholder="密码"> <button type="submit">登录</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { handleLogin() { // TODO: 发送请求到后端 } } } </script> <style scoped> .login-container { width:300px; margin:50px auto; padding:20px; border:1px solid #ddd; border-radius:10px; box-shadow:0010px rgba(0,0,0,0.1); } </style>
#### 注册功能接下来,我们需要创建一个注册组件。新建一个文件`Register.vue`:
html<template> <div class="register-container"> <h1>注册</h1> <form @submit.prevent="handleRegister"> <input type="text" v-model="username" placeholder="用户名"> <input type="password" v-model="password" placeholder="密码"> <button type="submit">注册</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { handleRegister() { // TODO: 发送请求到后端 } } } </script> <style scoped> .register-container { width:300px; margin:50px auto; padding:20px; border:1px solid #ddd; border-radius:10px; box-shadow:0010px rgba(0,0,0,0.1); } </style>
#### 登录和注册功能的实现现在,我们需要在`main.js`中引入登录和注册组件,并将它们添加到路由表中:
javascriptimport { createApp } from 'vue' import App from './App.vue' import router from './router' import Login from './components/Login.vue' import Register from './components/Register.vue' createApp(App).use(router).mount('#app') // 添加登录和注册路由router.addRoutes([ { path: '/login', component: Login }, { path: '/register', component: Register } ])
#### 登录和注册功能的测试最后,我们需要在`App.vue`中添加一个导航栏,包含登录和注册按钮:
html<template> <div class="app-container"> <nav> <ul> <li><router-link to="/">首页</router-link></li> <li><router-link to="/login">登录</router-link></li> <li><router-link to="/register">注册</router-link></li> </ul> </nav> </div> </template> <script> export default { // ... } </script> <style scoped> .app-container { width:100%; height:100vh; display: flex; justify-content: center; align-items: center; } nav ul { list-style: none; margin:0; padding:0; display: flex; } nav li { margin-right:20px; } nav a { color: #333; text-decoration: none; } nav a:hover { color: #666; } </style>
现在,我们可以测试登录和注册功能了。打开浏览器,访问` />
### 总结今天我们完成了知乎日报项目的第二天工作。我们实现了用户登录和注册功能,并将它们添加到路由表中。现在,我们可以测试这些功能了。
### 下一步明天,我们将继续完善我们的知乎日报项目。我们将重点关注文章发布和评论功能。
###代码下载如果你想下载完整的代码,可以访问以下链接:
* GitHub: GitLab: