Vue3中的hook

自定义hook函数

本质上hook是一个函数,把setup函数中使用的Composition API进行了封装。

类似于Vue2中的mixin

其使用目的是为了复用代码,让setup中的逻辑更加清楚易懂

SighIn.ts

/* eslint-disable no-unused-vars */
import { ref, Ref } from 'vue';
import { getPublicKeyAPI, loginAPI, LoginParam } from '@/api/userManage';
import { JSEncrypt } from 'jsencrypt';

export type Callback = () => void
export interface SignInState {
  publicKey: Ref<string>,
  token: Ref<string>,
  getPublicKey: (success?: Callback, fail?: Callback) => void,
  login: (param: LoginParam, success?: Callback, fail?: Callback) => void
}

class SignIn {
  publicKey = ref('')

  token = ref('')

  /**
   * 获取公钥
   * @param success 成功回调
   * @param fail 失败回调
   */
  getPublicKey(success?: Callback, fail?: Callback): void {
    getPublicKeyAPI()
      .then(({ data }: any) => {
        this.publicKey.value = data;
        success && success();
      })
      .catch(() => {
        fail && fail();
      });
  }

  /**
   * 登录
   * @param param
   * @param success
   * @param fail
   */
  login(param: LoginParam, success?: Callback, fail?: Callback): void {
    try {
      const toLogin = (): void => {
        // RSA 加密
        const jsencrypt = new JSEncrypt();
        jsencrypt.setPublicKey(this.publicKey.value);
        const RSApassword = jsencrypt.encrypt(param.credential);
        if (RSApassword) {
          param.credential = RSApassword;
          loginAPI(param).then(({ data }) => {
            this.token = data.token;
            localStorage.setItem('token', this.token.value);
            success && success();
          });
        } else {
          throw new Error();
        }
      };
      this.getPublicKey(toLogin);
    } catch (error) {
      fail && fail();
    }
  }
}

export default () => new SignIn();

猜你喜欢

转载自blog.csdn.net/dick_1999/article/details/121332691