1.0.1 • Published 8 months ago

@tangbin/vue-util v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

function utils lib

函数类工具库

Install

# npm
npm install --save @tangbin/util

# pnpm
pnpm add @tangbi/util

API

详细 API 文档请查看 函数类工具库

Usage

sso

import { defineComponent, watch } from 'vue';
import { sso } from '@tangbin/util';

export default defineComponent({
  mounted() {
    sso
      .login()
      .then((loginInfo) => {
        console.log('登录成功', loginInfo);
      })
      .catch((err) => {
        console.log('登录失败', err);
      });
  }
  setup() {
    return () => <div>login...</div>;
  },
});

request

import { message } from 'ant-design-vue';
import {
  ajax,
  get,
  post,
  upload,
  download,
  registerShowErrorMsgFn,
  registerExtraSuccessCodes,
} from '@tangbin/util';

// 注册通用错误回调方法
registerShowErrorMsgFn(message.error);

// 注册通用 ajax 请求成功返回码(默认返回码是数字200,传递第二个参数是用来替换默认值)
registerExtraSuccessCodes(['200', '0'], true);

// function ajax<T>(requestConfig: RequestConfig): Promise<T>
// 直接调用 ajax 方法,可以自由设置任何选项,特殊情况下可以调用
ajax({
  type: 'GET',
  url: '/module/fetch',
  // 如果需要自己处理错误信,可以设置为true
  customErrorMsg: true,
});

// function get<T>(url: string, params?: Record<string, any>, config?: RequestConfig): Promise<T>
get('/module/fetch', { name: 'abc', age: 123 }, { responseType: 'json' });

// function post<T>(url: string, params?: Record<string, any>, config?: RequestConfig): Promise<T>
post('/module/fetch', { name: 'abc', age: 123 }, { responseType: 'json' });

// function upload<T>(url: string, params: Record<string, any>, config?: RequestConfig): Promise<T>
upload('/module/upload', { name: 'abc', age: 123 }, { responseType: 'json' });

// function download({ gateway, prefix, downloadType, customErrorMsg, url, ...config }: RequestConfig): void
download({
  url: '/module/fetch',
  downloadType: 'excel',
});

interface Student {
  name: string;
  age: number;
}

export function query(id: number): Promise<Student> {
  return get('/student/query', { id });
}

query(1).then((student) => {
  console.log('fetch student success', student);
});

util

import { debounce, throttle, flatten, curry, compose } from '@tangbin/util';

const elem = document.getElementById('elem');

// 防抖函数
elem.addEventListener(
  'input',
  debounce(function (event) {
    console.log(event);
  }),
  false,
);

// 节流函数
window.addEventListener(
  'resize',
  throttle(function (event) {
    console.log(event);
  }),
  false,
);

// 数组扁平化
const arr = [1, 2, ['a', [true, false], 'b'], 3];
flatten(arr); // output: [1, 2, 'a', [true, false], 'b', 3]
flatten(arr, true); // output: [1, 2, 'a', true, false, 'b', 3]

// 函数柯里化
function add(x: number, y: number, z: number) {
  return x + y + z;
}
curry(add)(1)(2)(3); // output: 6
curry(add)(1, 2)(3); // output: 6

// 函数组合
function last(arr: string[]) {
  return arr[arr.length - 1];
}

function upper(str: string) {
  return str.toUpperCase();
}

const letters = ['a', 'b', 'c'];
compose([upper, last])(letters); // output: C

// 返回 Object.prototype.toString.call(val) = '[object xxx]' 中 xxx 部分的小写形式
typeOf(''); // output: string
typeOf(0); // output: number
typeOf(true); // output: boolean

// 深拷贝
const source = { name: 'aaa', age: 111 };
// 如果确定没有副作用,可以使用这个函数
deepCloneByJSON(source);
// 如果有副作用,使用这个函数
deepClone(source);

hooks

// src/@types/people.d.ts
export interface People {
  id?: number;
  name: string;
  age: number;
}

查询

// pages/people/detail.tsx
import { defineComponent, ref, reactive } from 'vue';
import { useFetch, fetch, query } from '@tangbin/util';
import { People } from 'src/@types/people';

export default defineComponent({
  setup() {
    const id = ref(0);
    const params = reactive({
      name: '',
      startTime: '',
      endTime: '',
    });

    // useFetch 和 useFetchWithLoading 用法相同,后者返回4个值,通过 setLoading 触发查询
    // const [info, setInfo, loading, setLoading] = useFetchWithLoading
    // 根据ID查询数据,value 必填,其他可选
    // fetch(url, id, flag)
    const info = useFetch<People>({
      url: '/a/b/c', //  如果不传 fn,则 url 必填
      // fn: fetch, // fn 默认既是 fetch
      value: { name: '', age: -1 },
      deps: [id],
      onBeforeFetch: () => !!id.value,
      onSuccess: (res) => {
        console.log('查询成功', res.name, res.age);
      },
      onError: (err) => {
        console.log('查询失败', err);
      },
      onComplete: () => {
        console.log('我在最后运行');
      },
    });

    // 普通查询
    // query(url, params = {}, flag)
    const students = useFetch<People[]>({
      url: '/a/b/c',
      fn: query,
      params: [params],
      value: [],
      deps: [params],
    });

    return () => <div>...</div>;
  },
});

添加/修改/删除

// pages/people/update/index.tsx
import { defineComponent } from 'vue';
import { useUpdateWithLoading, update } from '@tangbin/util';
import { People } from 'src/@types/people';

export default defineComponent({
  setup() {
    // useUpdate 和 useUpdateWithLoading 用法相同,后者返回4个值,通过 setLoading 触发查询
    // const [info, setInfo, loading, setLoading] = useFetchWithLoading
    // value 和 onBeforeFetch 必填,其他可选
    const [params, loading] = useUpdateWithLoading<People, boolean | null>({
      url: '/a/b/c', //  如果不传 fn,则 url 必填
      // fn: update, // fn 默认既是 update
      value: { id: 0, name: '', age: -1 },
      onBeforeFetch: (p) => !!p.name,
    });

    // 通过 setLoading(true) 启动
    const onAdd = () => {
      loading.value = true;
    };

    return () => <div>...</div>;
  },
});

分页查询

// pages/people/index.tsx
import { defineComponent, ref } from 'vue';
import { Form, Table } from 'ant-design-vue';
import { FormInstance } from 'ant-design-vue/es/form';
import { usePagination, paging, initPaginationParams } from '@tangbin/util';
import { People } from 'src/@types/people';

const Index: FC = () => {
  const form = ref<FormInstance>();

  // value, params 和 onBeforeFetch 必填,其他可选。
  const [data, loading, params, pagination] = usePagination<People>({
    url: '/a/b/c', //  如果不传 fn,则 url 必填
    // fn: paging, // fn 默认既是 paging
    value: initPaginationParams({}),
    // 如果使用了 ant design 的表单,可以提供 form 事例用于获取查询参数
    form,
    // 如果需要手动格式化,可以使用 formatParams 方法
    formatParams: (p: FetchParams) => {
      p.name = '_' + p.name;
      return p;
    },
    onBeforeFetch: () => true,
  });

  // 通过 setLoading(true) 启动, 或者分页(以及内置)
  const onSearch = (values) => {
    setParams({ ...params, ...values });
    setLoading(true);
  };

  return (
    <div>
      <Form ref={form} />
      <Table
        rowKey="id"
        loading={loading}
        columns={[]}
        dataSource={data}
        pagination={pagination}
      />
    </div>
  );
};

export default Index;
1.0.1

8 months ago

1.0.0

8 months ago