泽恩小站-教程区 Help

用户注册

前面把文章的 GET 请求实现得七七八八了。在继续开发发表文章、更新、删除之前,让我们换个口味,先实现用户管理。

本章搞定用户注册。

注册页面

新建 frontend/src/views/Login.vue 文件作为用户注册(以及登录)的页面,并写入代码:

<!-- frontend/src/views/Login.vue --> <template> <BlogHeader/> <div id="grid"> <div id="signup"> <h3>注册账号</h3> <form> <div class="form-elem"> <span>账号:</span> <input v-model="signupName" type="text" placeholder="输入用户名"> </div> <div class="form-elem"> <span>密码:</span> <input v-model="signupPwd" type="password" placeholder="输入密码"> </div> <div class="form-elem"> <button v-on:click.prevent="signup">提交</button> </div> </form> </div> <div> <!-- 留给后面章节的用户登录 --> </div> </div> <BlogFooter/> </template> <script> import axios from 'axios'; import BlogHeader from '@/components/BlogHeader.vue' import BlogFooter from '@/components/BlogFooter.vue' export default { name: 'Login', components: {BlogHeader, BlogFooter}, data: function () { return { signupName: '', signupPwd: '', signupResponse: null, } }, methods: { signup() { const that = this; axios .post('/api/user/', { username: this.signupName, password: this.signupPwd, }) .then(function (response) { that.signupResponse = response.data; alert('用户注册成功,快去登录吧!'); }) .catch(function (error) { alert(error.message); // Handling Error here... // https://github.com/axios/axios#handling-errors }); }, } } </script> <style scoped> #grid { display: grid; grid-template-columns: 1fr 1fr; } #signup { text-align: center; } .form-elem { padding: 10px; } input { height: 25px; padding-left: 10px; } button { height: 35px; cursor: pointer; border: none; outline: none; background: gray; color: whitesmoke; border-radius: 5px; width: 60px; } </style>

代码看起来有点多,但其实没有新知识 ;功能上就是将表单中的用户名和密码 post/api/user/ 接口,若创建成功则提醒用户前往登录,失败则将提示信息显示出来。

唯一需要注意的是, singup() 方法第一行的 const that = this ,它是为了 that.signupResponse = response.data 这里的调用而存在的。为什么要采取这种拐弯抹角的方式,而不直接调用 this ?这是因为在 JavaScript 中,**this是使用call方法调用函数时传递的第一个参数,它可以在函数调用时修改,在函数没有调用的时候,this的值无法确定。**直观来讲,如果这里的 .then() 方法里直接使用 this ,结果就是 this 未定义,语句报错。

那为什么之前的文章列表接口没有这个问题 ?这是因为当时用了箭头函数,其内部的 this 是遵循词法作用域,总是指向外层调用者 Vue 实例。

收尾工作

视图有了,接下来就是增加路由和入口等修修补补的工作了。

index.js 中添加注册路由:

// frontend/src/router/index.js ... const routes = [ ... { ... }, // 修改 Javascript 代码时 // 不要忘记在同级元素后加上逗号 // 否则将报错 // 后面章节类似 { path: "/login", name: "Login", component: Login } ]; ...

BlogHeader.vue 中添加入口:

<!-- frontend/src/components/BlogHeader.vue --> <template> <div id="header"> ... <hr> <div class="login"> <router-link to="/login" class="login-link">登录</router-link> </div> </div> </template> ... <style scoped> .login-link { color: black; } .login { text-align: right; padding-right: 5px; } </style>

OK 了,开启服务器看看效果:

P240 1

虽然比较简陋,但是具备了基本的注册功能。

课后作业

  • 优化登录失败时的错误提示。

  • 注册时通常需要输入两次密码,确保没有键入错误,请完成此功能。

Last modified: 06 January 2025