npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tangbin/vue-util

v1.0.1

Published

vue 函数类工具库

Downloads

1

Readme

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;