使用vue写登入注册代码,并与Django结合的代码例子
时间: 2023-12-03 16:42:45 浏览: 41
以下是一个使用 Vue.js 和 Django 开发的登陆/注册页面的代码示例。
首先,在 Vue.js 中创建一个名为 `Login.vue` 的单文件组件。该组件包含了两个文本框输入用户名和密码,以及两个按钮进行登陆和注册操作。
```html
<template>
<div>
<h1>Login</h1>
<form>
<div>
<label for="username">Username:</label>
<input type="text" v-model="username" id="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" v-model="password" id="password" required>
</div>
<div>
<button type="submit" @click.prevent="login">Login</button>
<button type="submit" @click.prevent="register">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
};
},
methods: {
login() {
// TODO: 登录逻辑
},
register() {
// TODO: 注册逻辑
},
},
};
</script>
```
下一步是编写与 Django 后端进行通信的代码。我们可以使用 Axios 库来发送 HTTP 请求。需要注意的是,在进行跨域请求时,Django 后端需要启用 CORS(跨域资源共享)。
```js
import axios from 'axios';
const API_URL = 'http://localhost:8000/api/'; // Django 后端的 API 地址
export default {
login(username, password) {
return axios.post(`${API_URL}login/`, { username, password });
},
register(username, password) {
return axios.post(`${API_URL}register/`, { username, password });
},
};
```
最后,在 Django 后端编写视图函数来处理登陆和注册请求。
```python
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'success': True})
else:
return JsonResponse({'success': False, 'message': 'Invalid credentials'})
def register_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
User.objects.create_user(username=username, password=password)
return JsonResponse({'success': True})
```
通过上述步骤,我们可以实现一个基本的登陆/注册页面,并与 Django 后端进行通信。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)