用户相关接口

登录注册分析

接口分析
	1.校验手机号是否存在接口
 	2.多方式登录接口:用户名/手机号/邮箱  +密码都可以登录
	3.发送手机验证码接口 (借助于第三方短信平台)
 	4.注册接口
 	5.校验手机是否存在接口

手机号是否存在接口

思路:手机号是否存在,是跟用户相关的,肯定在user的app中,我们首先确定手机号是否存在发送get请求,然后通过数据库查询来返回给前端
 
基础版本:
    class UserView(GenericViewSet):
    @action(methods=['GET'], detail=False)
    def send_msm(self, request, *args, **kwargs):
        # 从请求头中拿手机号
        phone = request.query_params.get('phone')
        if phone:
            user = User.objects.filter(phone=phone).first()
            if user:
                return APIResponse(code=100, msg='手机号已存在')
            else:
                return APIResponse(code=100, msg='手机号不正确')
        else:
            return APIResponse(code=101, msg='手机号必填')
        
'我们可以看到有很多的if判断,取到值以及取不到值的情况,因为我们有全局异常捕获,我们可以取到值就走到最后,没有取到值就直接让全局异常报错,改变代码'

class UserView(GenericViewSet):
    @action(methods=['GET'], detail=False)
    def send_msm(self, request, *args, **kwargs):
        try:
            # 从请求头中拿手机号,索引取值会报错,会被异常捕获,get拿不到返回的是None
            phone = request.query_params['phone']
            # 我们想要这句话报错,就不能用first,是不会报错的,可以用get或直接索引取值
            User.objects.get(phone=phone)
        except Exception as e:
            raise e
        return APIResponse(code=100, msg='手机号已存在')
"""
被try包裹的,我们就两个思路,第一个是正确拿到值,那么就直接走,拿不到我们就直接让报错,然后被异常捕获
"""

视图函数模板

    def send_sms(self, request, *args, **kwargs):
        try:
            # 放心大胆写
        except Exception as e:
            raise e
        return APIResponse()

多方式登录接口

使用 用户名,手机号,邮箱+密码登录
后端无法识别发出来的是用户名是什么:
    所以用户名可能是用户名,也可能是手机号,更可能是邮箱

视图类

from rest_framework.viewsets import GenericViewSet
from .models import User
from rest_framework.decorators import action
from utils.common_reponse import APIResponse
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from .user_serializer import UserLoginSerializer


class UserView(GenericViewSet):
    # 使用序列化类就需要配置
    queryset = User.objects.filter(is_active=True)
    serializer_class = UserLoginSerializer

    @action(methods=['GET'], detail=False)
    def send_msm(self, request, *args, **kwargs):
        try:
            # 从请求头中拿手机号,索引取值会报错,会被异常捕获,get拿不到返回的是None
            phone = request.query_params['phone']
            # 我们想要这句话报错,就不能用first,是不会报错的,可以用get或直接索引取值
            User.objects.get(phone=phone)
        except Exception as e:
            raise e
        return APIResponse(code=100, msg='手机号已存在')

    # 多方式登录接口
    # @action(methods=['POST'], detail=False)
    # def login_mul(self, request, *args, **kwargs):
    #     """
    #     拿到前端传来的用户名和密码,校验用户是否存在和密码是否正确,正确签发token
    #     """
    #     username = request.data.get('username')
    #     password = request.data.get('password')
    #     # 直接将用户名传到序列化类中
    #
    #     user = User.objects.filter(username=username).first()
    #     if user and user.check_password(password):
    #         # 用户名和密码都存在,那么再签发token,用jwt来签发
    #         payload = jwt_payload_handler(user)
    #         token = jwt_encode_handler(payload)
    #         return APIResponse(token=token, username=user.username)
    #     else:
    #         return APIResponse(code=101, msg='用户名或者密码不正确')

    """
    现在开始代码优化,我们在序列化类中去校验,而且用户名要判断是名字还是邮箱,还是手机号
    """

    @action(methods=['POST'], detail=False)
    def login_mul(self, request, *args, **kwargs):
        """
        拿到前端传来的用户名和密码,校验用户是否存在和密码是否正确,正确签发token
        """
        # 直接将用户名传到序列化类中,先实例化序列化类的对象,self.get_serializer其实拿到的是就是序列化类
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        # 这一步直接调用序列化类,参数表示如果返回值不是True的话,会直接向上抛异常
        # 校验通过的话,我们就可以拿到我们写在context里面的用户名和token
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(token=token, username=username)

序列化类

from rest_framework import serializers
from .models import User
import re
from rest_framework.exceptions import ValidationError
from rest_framework.exceptions import APIException
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class UserLoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField(min_length=2, max_length=12)

    class Meta:
        model = User
        # 这个序列化类我们不用序列化以及反序列化,只是用来做全局钩子的校验
        fields = ['username', 'password']  # 这里写的相当于映射过来,因为Auth表字段username有唯一值限制,所以我们要重写这个字段

    # 全局钩子
    def validate(self, attrs):
        # attrs就是前端传过来的数据,为了可扩展性,我们可以把获取user用户对象和获取token写成方法,方便以后调用
        user = self._get_user(attrs)
        token = self._get_token(user)
        # 给序列化类的对象添加一些对象,context这个方法是一个字典就是用来沟通的桥梁
        self.context['username'] = user.username
        self.context['token'] = token
        # 全局钩子校验结束,要返回出去
        return attrs

    def _get_user(self, attrs):
        # 这里是获得用户对象的方法
        username = attrs.get('username')
        password = attrs.get('password')
        # 下面是用户名的校验,需要判断是用户名还是邮箱,还是手机号,需要用正则

        if re.match(r'^1[3-9][0-9]{9}$', username):  # 判断是否符合这个,如果符合证明是手机号
            user = User.objects.filter(phone=username).first()  # 根据手机号查到用户对象
        elif re.match(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', username):
            user = User.objects.filter(email=username).first()
        else:
            user = User.objects.filter(username=username).first()
        # 然后再判断密码是否正确
        if user and user.check_password(password):  # 如果用户名和密码都存在,则证明用户没问题
            return user  # 将用户对象返回出去
        # 如果不是的话,全局钩子就要抛异常
        raise APIException('用户名或密码错误')
        # raise ValidationError('用户名或密码错误')

    def _get_token(self, user):
        # 这里是获取token的方法
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

腾讯云短信申请

# 发送短信接口,借助于第三方短信平台,收费的
	-腾讯云短信
 	-阿里 大于短信
 	-。。。
   
# 申请微信公众号,自己搜 实名认证 

# 使用腾讯短信
	-https://cloud.tencent.com,微信扫码登录
    -搜索短信:https://console.cloud.tencent.com/smsv2
    - 创建短信签名:公众号注册,提交等待审核
	- 创建短信正文模版
	-等待审核
	-发送短信
    	python 代码法搜昂短信
        
        
        
        
 # API SDK
	-API: 咱们学习过的API接口,写起来比较麻烦,自己分析接口
    
    -SDK:集成开发工具包,分语言,java,python,go
    	-使用python 对api进行封装成包
        -以后我们只需要,安装包,导入包,包名.发送短信,传入参数,就可以发送了
    

   - 只要官方提供sdk,优先用sdk
		pip install tencentcloud-sdk-python

腾讯云短信开发

给手机发送短信---》第三方平台,腾讯云短讯

# API和SDK,有SDK优先用SDK

sdk:
   3.0版本,云操作的sdk,不仅仅有发送短信,还有云功能的其他功能
	2.0版本,简单,只有发送短信功能
   
安装sdk;
	-方式一:pip install tencentcloud-sdk-python
 	-方式二源码安装:
        -下载源码
        -执行 python steup.py install

封装发送短信

-libs下创建send_sms_v3文件夹:
    _init__.py
    settings.py
    sms.py
 
# __init__.py,这样做的目的是导入文件的时候可以少写一点
from .sms import get_code,send_sms

# 我们在settings.py里面写发送短信的一些配置
SECRET_ID = ''
SECRET_KEY = ''
APP_ID = ''
SIGN_NAME = ''
TEMPLATE_ID = ''

# 生成随机4位数字验证码函数
import random
def get_code(number=4):
    code = ''
    for i in range(number):
        code += str(random.randint(0, 9))  # python 是强类型语言,不同类型运算不允许
    return code

# 发送短信函数
def send_sms(code, mobile):
    try:
        cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()

        req.SmsSdkAppId = settings.APP_ID
        req.SignName = settings.SIGN_NAME
        req.TemplateId = settings.TEMPLATE_ID
        # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
        req.TemplateParamSet = [code, '1']
        # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86" + mobile, ]
        # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.ExtendCode = ""
        # 国际/港澳台短信 senderid(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.SenderId = ""
        resp = client.SendSms(req)
        # 输出json格式的字符串回包
        res = json.loads()
        if res.get('SendStatusSet')[0].get('Code') == 'Ok':
            return True
        else:
            return False
    except TencentCloudSDKException as err:
        print(err)
        return False

短信验证码接口

class UserView(GenericViewSet):
   # 发送短信验证码接口

    @action(methods=['POST'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        try:
            # 获取前端发过来需要发送验证码的手机号
            phone = request.data['phone']
            # 调用获取随机验证码数字
            code = get_code()
            # 将随机验证码数据存在cache中
            cache.set('sms_code %s' % phone, code)
            # 调用发送短信验证码接口,返回值是True或者False,如果是True的话证明发送成功,如果不是的话就是发送失败了
            res = send_code(code, phone)
            if res:
                return APIResponse(msg='短信发送成功')
            else:
                raise APIException('短信发送失败')
        except Exception as e:
            raise APIException(str(e))

短信登录接口

前端---》{mobile:122334,code:8888}---->post----》
视图类中方法逻辑:
    1.取出前端传来的手机号和验证码
    2.校验验证码是否正确(发送验证码接口存了验证码,从cache里面取)
    3.验证码正确的话根据手机号查用户
    4.可以查到用户就可以签发token
    5.返回给前端

视图类

class UserView(GenericViewSet):
    # 使用序列化类就需要配置
    queryset = User.objects.filter(is_active=True)
    serializer_class = UserLoginSerializer

    # 重写get_serializer_class方法,不同视图函数用到不同的序列化类
    def get_serializer_class(self):
        if self.action == 'sms_login':
            return SmsLoginSerializer
        else:
            return super().get_serializer_class()

    # 将登录功能进行封装,这样不管是账号密码还是手机号验证码登录直接调用就可以
    def _login(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(token=token, username=username)


    """
    现在开始代码优化,我们在序列化类中去校验,而且用户名要判断是名字还是邮箱,还是手机号
    """

    @action(methods=['POST'], detail=False)
    def login_mul(self, request, *args, **kwargs):
        """
        拿到前端传来的用户名和密码,校验用户是否存在和密码是否正确,正确签发token
        """
        # 直接将用户名传到序列化类中,先实例化序列化类的对象,self.get_serializer其实拿到的是就是序列化类
        return self._login(request, *args, **kwargs)



    # 短信登录接口
    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        # 直接调用封装起来的登录接口,返回返回值就可以啦
        return self._login(request, *args, **kwargs)

序列化类

from rest_framework import serializers
from .models import User
import re
from rest_framework.exceptions import APIException
from rest_framework_jwt.settings import api_settings
from django.core.cache import cache

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


# 封装的序列化类所有方法的父类,序列化在反序列化校验的时候,必须走全局钩子,所以我们在其他地方写,只要走全局钩子,这个类
# 写在前面,就会走这个类的全局钩子
class BaseLoginSerializer:
    # 全局钩子
    def validate(self, attrs):
        # attrs就是前端传过来的数据,为了可扩展性,我们可以把获取user用户对象和获取token写成方法,方便以后调用
        user = self._get_user(attrs)
        token = self._get_token(user)
        # 给序列化类的对象添加一些对象,context这个方法是一个字典就是用来沟通的桥梁
        self.context['username'] = user.username
        self.context['token'] = token
        # 全局钩子校验结束,要返回出去
        return attrs

    def _get_user(self):
        raise APIException('继承这个类必须重写这个方法')

    def _get_token(self, user):
        # 这里是获取token的方法
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token


class UserLoginSerializer(BaseLoginSerializer, serializers.ModelSerializer):
    username = serializers.CharField(min_length=2, max_length=12)

    class Meta:
        model = User
        # 这个序列化类我们不用序列化以及反序列化,只是用来做全局钩子的校验
        fields = ['username', 'password']  # 这里写的相当于映射过来,因为Auth表字段username有唯一值限制,所以我们要重写这个字段

    def _get_user(self, attrs):
        # 这里是获得用户对象的方法
        username = attrs.get('username')
        password = attrs.get('password')
        # 下面是用户名的校验,需要判断是用户名还是邮箱,还是手机号,需要用正则
        if re.match(r'^1[3-9][0-9]{9}$', username):  # 判断是否符合这个,如果符合证明是手机号
            user = User.objects.filter(phone=username).first()  # 根据手机号查到用户对象
        elif re.match(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', username):
            user = User.objects.filter(email=username).first()
        else:
            user = User.objects.filter(username=username).first()
        # 然后再判断密码是否正确
        if user and user.check_password(password):  # 如果用户名和密码都存在,则证明用户没问题
            return user  # 将用户对象返回出去
        # 如果不是的话,全局钩子就要抛异常
        raise APIException('用户名或密码错误')
        # raise ValidationError('用户名或密码错误')

短信注册接口

前端---》{mobile:1888344,code:8888,password:123}--->post
后端 视图类

路由

# http://127.0.0.1:8000/api/v1/user/register/   --->post 请求
router.register('register',views.RegisterUserView,'register')

视图类

class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = User.objects.filter(is_active=True)
    serializer_class = RegisterSerializer
	# 重写了create方法,是为了避免源码的create方法返回序列化类的data,这样就不会走序列化
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg='注册成功')

序列化类

class RegisterSerializer(serializers.ModelSerializer):
    # code不是表里面的字段,所以要重写该字段,因为只反序列化用,所以加参数
    code = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['code', 'password', 'phone']
        extra_kwargs = {'password': {'write_only': True}}
	# 全局钩子,用来判断验证码是否正确,然后弹出验证码,将用户名和手机号设为一致返回出去
    def validate(self, attrs):
        code = attrs.get('code')
        phone = attrs.get('phone')
        if code == cache.get('sms_code %s' % phone):
            attrs.pop("code")
            attrs['username'] = phone
        else:
            raise APIException('验证码错误')
        return attrs
	# 这个是序列化类的create方法,当序列化对象.save()方法的时候会调用序列化类中的create方法进行保存数据,因为本身的create方法创建数据库是create,但是auth表需要用create_user所以需要重写该方法
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

登录与注册前端

登录页面分析

点击登录,弹出登录组件,盖住整个屏幕(定位)
点击登录组件中的x,关闭登录组件(子传父)

测试:login.vue

<template>
  <div class="login">
    <span style="padding: 50px" @click="closeLogin">X</span>
  </div>
</template>

<script>
export default {
  name: "Login",
  methods:{
    closeLogin(){
      this.$emit('go_close')

    }
  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>

测试;Header.vue

  <div class="right-part">
        <div>
          <span @click="goLogin">登录</span>
          <span class="line">|</span>
          <span>注册</span>
        </div>
      </div>
    </div>

    <Login v-if="login_show" @go_close="goClose"></Login>
    
    
   goLogin() {
      this.login_show = true

    },
    goClose() {
      this.login_show = false
    }

登录页面

Login.vue

<template>
  <div class="login">
    <div class="box">
      <i class="el-icon-close" @click="close_login"></i>
      <div class="content">
        <div class="nav">
          <span :class="{active: login_method === 'is_pwd'}"
                @click="change_login_method('is_pwd')">密码登录</span>
          <span :class="{active: login_method === 'is_sms'}"
                @click="change_login_method('is_sms')">短信登录</span>
        </div>

        <el-form v-if="login_method === 'is_pwd'">
          <el-input
              placeholder="用户名/手机号/邮箱"
              prefix-icon="el-icon-user"
              v-model="username"
              clearable>
          </el-input>
          <el-input
              placeholder="密码"
              prefix-icon="el-icon-key"
              v-model="password"
              clearable
              show-password>
          </el-input>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form>

        <el-form v-if="login_method === 'is_sms'">
          <el-input
              placeholder="手机号"
              prefix-icon="el-icon-phone-outline"
              v-model="mobile"
              clearable
              @blur="check_mobile">
          </el-input>
          <el-input
              placeholder="验证码"
              prefix-icon="el-icon-chat-line-round"
              v-model="sms"
              clearable>
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
          <el-button @click="mobile_login" type="primary">登录</el-button>
        </el-form>

        <div class="foot">
          <span @click="go_register">立即注册</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: '',
      password: '',
      mobile: '',
      sms: '',  // 验证码
      login_method: 'is_pwd',
      sms_interval: '获取验证码',
      is_send: false,
    }
  },
  methods: {
    close_login() {
      this.$emit('close')
    },
    go_register() {
      this.$emit('go')
    },
    change_login_method(method) {
      this.login_method = method;
    },
    check_mobile() {
      if (!this.mobile) return;
      // js正则:/正则语法/
      // '字符串'.match(/正则语法/)
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      // 手机号前端校验通过---》开始后端手机号是否存在的校验
      // 后台校验手机号是否已存在
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/is_phone/',
        method: 'get',
        params:{
          phone:this.mobile
        }
      }).then(response => {
        // code 如果是100,说明手机号存在,登录功能,才能发送短信
        // ==   只比较值是否相等
        // ===  即比较值,又比较类型
        if (response.data.code == 100) {
          this.$message({
            message: '账号正常',
            type: 'success',
            duration: 1000,
          });
          // 发生验证码按钮才可以被点击
          this.is_send = true;
        } else {
          this.$message({
            message: '账号不存在',
            type: 'warning',
            duration: 1000,
            onClose: () => {
              this.mobile = '';
            }
          })
        }
      }).catch(() => {
      });
    },
    send_sms() {
      // this.is_send 如果是false,函数直接结束,就不能发送短信
      if (!this.is_send) return;
      // 按钮点一次立即禁用
      this.is_send = false;

      let sms_interval_time = 60;
      this.sms_interval = "发送中...";

      // 定时器: setInterval(fn, time, args)

      // 往后台发送验证码
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/send_sms/',
        method: 'post',
        data: {
          phone: this.mobile
        }
      }).then(response => {
        if (response.data.code == 100) { // 发送成功
          // 启动定时器
          let timer = setInterval(() => {
            if (sms_interval_time <= 1) {
              clearInterval(timer);
              this.sms_interval = "获取验证码";
              this.is_send = true; // 重新回复点击发送功能的条件
            } else {
              sms_interval_time -= 1;
              this.sms_interval = `${sms_interval_time}秒后再发`;
            }
          }, 1000);
        } else {  // 发送失败
          this.sms_interval = "重新获取";
          this.is_send = true;
          this.$message({
            message: '短信发送失败',
            type: 'warning',
            duration: 3000
          });
        }
      }).catch(() => {
        this.sms_interval = "频率过快";
        this.is_send = true;
      })


    },
    login() {
      if (!(this.username && this.password)) {
        this.$message({
          message: '请填好账号密码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/login_mul/',
        method: 'post',
        data: {
          username: this.username,
          password: this.password,
        }
      }).then(response => {
        let username = response.data.username;
        let token = response.data.token;
        if(!username){
          this.$message('用户不存在')
        }
        else{
        this.$cookies.set('username', username, '7d');
        this.$cookies.set('token', token, '7d');
        this.$emit('success');}
      }).catch(error => {
        console.log(error.response.data)
      })
    },
    mobile_login() {
      if (!(this.mobile && this.sms)) {
        this.$message({
          message: '请填好手机与验证码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/sms_login/',
        method: 'post',
        data: {
          phone: this.mobile,
          code: this.sms,
        }
      }).then(response => {
        let username = response.data.username
        let token = response.data.token
        // 放到cookie中,7天过期
        if(response.data.code==999){
          this.$message('验证码不正确')
        }
        else{
        this.$cookies.set('username', username, '7d')
        this.$cookies.set('token', token, '7d')
        // 关闭登录框
        this.$emit('success')
        }

      }).catch(error => {
        console.log(error.response.data)
      })
    }
  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.7);
}

.box {
  width: 400px;
  height: 420px;
  background-color: white;
  border-radius: 10px;
  position: relative;
  top: calc(50vh - 210px);
  left: calc(50vw - 200px);
}

.el-icon-close {
  position: absolute;
  font-weight: bold;
  font-size: 20px;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.el-icon-close:hover {
  color: darkred;
}

.content {
  position: absolute;
  top: 40px;
  width: 280px;
  left: 60px;
}

.nav {
  font-size: 20px;
  height: 38px;
  border-bottom: 2px solid darkgrey;
}

.nav > span {
  margin: 0 20px 0 35px;
  color: darkgrey;
  user-select: none;
  cursor: pointer;
  padding-bottom: 10px;
  border-bottom: 2px solid darkgrey;
}

.nav > span.active {
  color: black;
  border-bottom: 3px solid black;
  padding-bottom: 9px;
}

.el-input, .el-button {
  margin-top: 40px;
}

.el-button {
  width: 100%;
  font-size: 18px;
}

.foot > span {
  float: right;
  margin-top: 20px;
  color: orange;
  cursor: pointer;
}

.sms {
  color: orange;
  cursor: pointer;
  display: inline-block;
  width: 70px;
  text-align: center;
  user-select: none;
}
</style>

注册页面

Register.vue

<template>
  <div class="register">
    <div class="box">
      <i class="el-icon-close" @click="close_register"></i>
      <div class="content">
        <div class="nav">
          <span class="active">新用户注册</span>
        </div>
        <el-form>
          <el-input
              placeholder="手机号"
              prefix-icon="el-icon-phone-outline"
              v-model="mobile"
              clearable
              @blur="check_mobile">
          </el-input>
          <el-input
              placeholder="密码"
              prefix-icon="el-icon-key"
              v-model="password"
              clearable
              show-password>
          </el-input>
          <el-input
              placeholder="验证码"
              prefix-icon="el-icon-chat-line-round"
              v-model="sms"
              clearable>
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
          <el-button @click="register" type="primary">注册</el-button>
        </el-form>
        <div class="foot">
          <span @click="go_login">立即登录</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Register",
  data() {
    return {
      mobile: '',
      password: '',
      sms: '',
      sms_interval: '获取验证码',
      is_send: false,
    }
  },
  methods: {
    close_register() {
      this.$emit('close', false)
    },
    go_login() {
      this.$emit('go')
    },
    check_mobile() {
      if (!this.mobile) return;
      // js正则:/正则语法/
      // '字符串'.match(/正则语法/)
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      // 后台校验手机号是否已存在
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/is_phone/',
        method: 'get',
        params: {
          phone: this.mobile
        }
      }).then(response => {
        // 手机号不存在,才能发送短信,才能注册
        if (response.data.code != 100) {
          this.$message({
            message: '欢迎注册我们的平台',
            type: 'success',
            duration: 1500,
          });
          // 发生验证码按钮才可以被点击
          this.is_send = true;
        } else {
          this.$message({
            message: '账号已存在,请直接登录',
            type: 'warning',
            duration: 1500,
          })
        }
      }).catch(() => {
      });
    },
    send_sms() {
      // this.is_send必须允许发生验证码,才可以往下执行逻辑
      if (!this.is_send) return;
      // 按钮点一次立即禁用
      this.is_send = false;

      let sms_interval_time = 60;
      this.sms_interval = "发送中...";

      // 往后台发送验证码
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/send_sms/',
        method: 'post',
        data: {
          phone: this.mobile
        }
      }).then(response => {
        if (response.data.code == 100) { // 发送成功
          let timer = setInterval(() => {
            if (sms_interval_time <= 1) {
              clearInterval(timer);
              this.sms_interval = "获取验证码";
              this.is_send = true; // 重新回复点击发送功能的条件
            } else {
              sms_interval_time -= 1;
              this.sms_interval = `${sms_interval_time}秒后再发`;
            }
          }, 1000);
        } else {  // 发送失败
          this.sms_interval = "重新获取";
          this.is_send = true;
          this.$message({
            message: '短信发送失败',
            type: 'warning',
            duration: 3000
          });
        }
      }).catch(() => {
        this.sms_interval = "频率过快";
        this.is_send = true;
      })


    },
    register() {
      if (!(this.mobile && this.sms && this.password)) {
        this.$message({
          message: '请填好手机、密码与验证码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/register/',
        method: 'post',
        data: {
          phone: this.mobile,
          code: this.sms,
          password: this.password
        }
      }).then(response => {
        if (response.data.code == 999) {
          this.$message({
            message: '验证码错误',
            type: 'warning',
            duration: 1500,
            showClose: true,
            onClose: () => {
              // 清空所有输入框
              this.sms = '';
            }
          });
        } else {
          this.$message({
            message: '注册成功,3秒跳转登录页面',
            type: 'success',
            duration: 3000,
            showClose: true,
            onClose: () => {
              // 去向成功页面
              this.$emit('success')
            }
          });
        }
      }).catch(error => {
        this.$message({
          message: '注册失败,请重新注册',
          type: 'warning',
          duration: 1500,
          showClose: true,
          onClose: () => {
            // 清空所有输入框
            this.mobile = '';
            this.password = '';
            this.sms = '';
          }
        });
      })
    }
  }
}
</script>

<style scoped>
.register {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.3);
}

.box {
  width: 400px;
  height: 480px;
  background-color: white;
  border-radius: 10px;
  position: relative;
  top: calc(50vh - 240px);
  left: calc(50vw - 200px);
}

.el-icon-close {
  position: absolute;
  font-weight: bold;
  font-size: 20px;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.el-icon-close:hover {
  color: darkred;
}

.content {
  position: absolute;
  top: 40px;
  width: 280px;
  left: 60px;
}

.nav {
  font-size: 20px;
  height: 38px;
  border-bottom: 2px solid darkgrey;
}

.nav > span {
  margin-left: 90px;
  color: darkgrey;
  user-select: none;
  cursor: pointer;
  padding-bottom: 10px;
  border-bottom: 2px solid darkgrey;
}

.nav > span.active {
  color: black;
  border-bottom: 3px solid black;
  padding-bottom: 9px;
}

.el-input, .el-button {
  margin-top: 40px;
}

.el-button {
  width: 100%;
  font-size: 18px;
}

.foot > span {
  float: right;
  margin-top: 20px;
  color: orange;
  cursor: pointer;
}

.sms {
  color: orange;
  cursor: pointer;
  display: inline-block;
  width: 70px;
  text-align: center;
  user-select: none;
}
</style>

Header.vue

<template>
  <div class="header">
    <div class="slogan">
      <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
    </div>
    <div class="nav">
      <ul class="left-part">
        <li class="logo">
          <router-link to="/">
            <img src="../assets/img/head-logo.svg" alt="">
          </router-link>
        </li>
        <li class="ele">
          <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
        </li>
      </ul>

      <div class="right-part">
        <div v-if="!username">
          <span @click="put_login">登录</span>
          <span class="line">|</span>
          <span @click="put_register">注册</span>
        </div>
        <div v-else>
          <span>{{ username }}</span>
          <span class="line">|</span>
          <span>注销</span>
        </div>
      </div>
    </div>
    <Login v-if="is_login" @close="close_login" @go="put_register" @success="success_login"/>
    <Register v-if="is_register" @close="close_register" @go="put_login" @success="success_register"/>
  </div>

</template>

<script>
import Login from "@/components/Login";

import Register from "@/components/Register";

export default {
  name: "Header",
  data() {
    return {
      // 当前所在路径,去sessionStorage取的,如果取不到,就是 /
      url_path: sessionStorage.url_path || '/',
      is_login: false,
      is_register: false,
      username: this.$cookies.get('username'),
      token: this.$cookies.get('token'),
    }
  },
  methods: {
    goPage(url_path) {
      // 已经是当前路由就没有必要重新跳转
      if (this.url_path !== url_path) {
        this.$router.push(url_path);
      }
      sessionStorage.url_path = url_path;
    },
    put_login() {
      this.is_login = true;
      this.is_register = false;
    },
    put_register() {
      this.is_login = false;
      this.is_register = true;
    },
    close_login() {
      this.is_login = false;
    },
    close_register() {
      this.is_register = false;
    },
    success_login() {
      this.is_login = false;
      this.username = this.$cookies.get('username')
      this.token = this.$cookies.get('token')
    },
    success_register() {
      this.is_login = true
      this.is_register = false

    }
  },
  created() {
    // 组件加载万成,就取出当前的路径,存到sessionStorage  this.$route.path
    sessionStorage.url_path = this.$route.path;
    // 把url_path = 当前路径
    this.url_path = this.$route.path;
  },
  components: {
    Login,
    Register
  }
}
</script>

<style scoped>
.header {
  background-color: white;
  box-shadow: 0 0 5px 0 #aaa;
}

.header:after {
  content: "";
  display: block;
  clear: both;
}

.slogan {
  background-color: #eee;
  height: 40px;
}

.slogan p {
  width: 1200px;
  margin: 0 auto;
  color: #aaa;
  font-size: 13px;
  line-height: 40px;
}

.nav {
  background-color: white;
  user-select: none;
  width: 1200px;
  margin: 0 auto;

}

.nav ul {
  padding: 15px 0;
  float: left;
}

.nav ul:after {
  clear: both;
  content: '';
  display: block;
}

.nav ul li {
  float: left;
}

.logo {
  margin-right: 20px;
}

.ele {
  margin: 0 20px;
}

.ele span {
  display: block;
  font: 15px/36px '微软雅黑';
  border-bottom: 2px solid transparent;
  cursor: pointer;
}

.ele span:hover {
  border-bottom-color: orange;
}

.ele span.active {
  color: orange;
  border-bottom-color: orange;
}

.right-part {
  float: right;
}

.right-part .line {
  margin: 0 10px;
}

.right-part span {
  line-height: 68px;
  cursor: pointer;
}
</style>
posted @ 2023-03-03 19:09  雪语  阅读(33)  评论(0编辑  收藏  举报