Giter Club home page Giter Club logo

vue-hooks-plus's Introduction

npm package build status language librariesio LICENSE

VueHooks Plus

English | 简体中文

High performance & Simplicity Vue3 Hooks library

✨ Features

  • 🏄🏼‍♂️ Easy to learn and use
  • 🔋 Supports SSR
  • 🛸 Contains a comprehensive collection of basic Hooks
  • 🏟️ A wide range of application scenarios
  • 🦾 Preferred useRequest, Powerful request middle tier
  • 🎪 Interactive demo, immersive
  • 🎯 Written in TypeScript with predictable static types
  • 🪄 Support the on-demand load, and reduce the packing volume
  • 🤺 Playground, there's ample scope for one's abilities
  • 🔐 Perfect test, safe and reliable

📦 Install

npm i vue-hooks-plus

CDN

<script src="https://cdn.jsdelivr.net/npm/vue-hooks-plus/dist/js/index.iife.js"></script>

It will be exposed to global as VueHooks_Plus

🤹‍♀️ Usage

import { useRequest } from 'vue-hooks-plus'

Introduced on demand

import useRequest from 'vue-hooks-plus/es/useRequest'

Auto Import

Vite
import AutoImport from 'unplugin-auto-import/vite'
import { VueHooksPlusResolver } from '@vue-hooks-plus/resolvers'

export const AutoImportDeps = () =>
  AutoImport({
    imports: ['vue', 'vue-router'],
    include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
    dts: 'src/auto-imports.d.ts',
    resolvers: [VueHooksPlusResolver()],
  })


Webpack
const { VueHooksPlusResolver } = require('@vue-hooks-plus/resolvers')
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/webpack')({
      imports: ['vue', 'vue-router'],
      include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
      dts: 'src/auto-imports.d.ts',
      resolvers: [VueHooksPlusResolver()],
    }),
  ],
}


For other supported tools, please see unplugin-auto-import

Globalization Documentations

Example

🤩 Awesome

Template

🪴 Project Activity

Alt

Contributing

Welcome to join us! You can check out the Contributing Guide to learn how to get started.

Contributors

Thanks for all their contributions 🐝 !

🌸 Thanks

This project is heavily inspired by the following awesome projects.

📄 License

MIT License © 2022-PRESENT YongGit

vue-hooks-plus's People

Contributors

belazy-h avatar colgin avatar dependabot[bot] avatar erikkkwu avatar hongaah avatar inhiblab avatar nelsonyong avatar noobbbbbbb avatar vaseala avatar xiaodaigua-ray avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-hooks-plus's Issues

1.6.5升级到1.7.4useUrlState报错

Describe the bug

image
如图,参照官网例子获取url参数报错
官网例子也无法正常使用
image

Steps to reproduce

在axios中使用
const default_state = { token: "" };
let url_token = useUrlState(default_state, { localStorageKey: "localStorageKey", });
image

System Info

windows 11
edge

Used Package Manager

pnpm

Validations

有考虑将userequest独立出来吗

Description

使用中已经有其他的use相关工具依赖包了,更多是倾向于只引入一个userequest做请求使用。

Suggested solution

希望能独立成@namespace/userequest包

Alternative

No response

Additional context

No response

Validations

祝大家新年快乐 🧨

Description

VueHooks Plus 团队提前预祝大家新年快乐 🧨

Suggested solution

  • 钱兔 🐰 无量

Alternative

No response

Additional context

No response

Validations

useKeyPress方法会在控制台打印,

Describe the bug

image
这个方法会在控制台打印.希望作者能删除打印的代码

Steps to reproduce

No response

System Info

"vue-hooks-plus": "^1.6.0-alpha.2"

Used Package Manager

npm

Validations

loadingDelay配合element-plus中的v-loading指令一起使用时异常

这个问题很奇怪,打印 loading 值显示的是 false, 但是将值传入到 v-loading 时,delayLoading 好像就失效了,部分代码如下:

<script  lang="ts" setup>
function getUsername(): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('vue-hooks-plus useRequest');
    }, 4000);
  });
}

const { data, loading } = useRequest(() => getUsername(), {
  loadingDelay: 2000,
});
<script>

<template>
  <div v-loading="loading">
    <h1>🚀 loading {{ loading ? '加载中' : data }}</h1>
    <h1>😶‍🌫️ loading {{ loading }}</h1>

    <h2>🔥 myLoading: {{ myLoading }}</h2>
    <el-button @click="toggleMyLoading" type="primary">Element</el-button>
  </div>
</template>

在线链接:vue-hooks-plus-delayLoading - stackblitz
很明显可以看到,显示了2次loading。

我看源码,loadingDelay 好像用的是 useLoadingDelayPlugin

 onBefore: () => {
      cancelTimeout();
      timerRef.value = setTimeout(() => {
        fetchInstance.setState({
          loading: true,
        });
      }, (isRef(loadingDelay) ? loadingDelay.value : loadingDelay) as number);

      return {
        loading: false,
      };
    },

看这段代码好像没什么问题,还请大佬指点。
ps: element-plus loading

[ RFC ]: Add useRequest devtools

Description

useRequest devtool

  • read core option
  • watch request data
  • read plugins state

Suggested solution

Alternative

No response

Additional context

No response

Validations

useRequest轮询pollingInterval动态修改不起作用

  const { loading, run: runQueryData } = useRequest(
    () => queryData(),
    {
      manual: true,
      pollingInterval: generalStore.getPollingInterval,
      pollingWhenHidden: false,
      onSuccess: (res: any) => {
        if (res.data && res.data.length > 0) {
          chartsData.value = res.data;
        }
      },
    }
  );

修改pinia后无效,直接传入组件无效,是不是手动的问题

🌸 Improving the README for External Hooks

Description

Improving the README for External Hooks, A comprehensive description can help users better understand this hook. 🌸

Suggested solution

Improving the README for External Hooks

Alternative

No response

Additional context

No response

Validations

[typescript]:Could not find a declaration file for module `js-cookie`

Describe the bug

packing project type error

Steps to reproduce

Run pnpm vue-tsc --noEmit

System Info

error TS7016: Could not find a declaration file for module 'js-cookie'. '/Users/yangjie/WebCode/Github/vite-vue-box/node_modules/.pnpm/[email protected]/node_modules/js-cookie/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/js-cookie` if it exists or add a new declaration (.d.ts) file containing `declare module 'js-cookie';`

1 import Cookies from 'js-cookie';
                      ~~~~~~~~~~~
Found 1 error in node_modules/.pnpm/[email protected][email protected]/node_modules/vue-hooks-plus/lib/useCookieState/index.d.ts:1

Used Package Manager

pnpm

Validations

[useUrlState]: 🚜 The reconstruction was performed using vue-router

Description

At present, I use listening URL transformation, combined with view linkage, but I think its concept is different from what vue advocated. I hope these things help me within vue, rather than manually by myself.

Suggested solution

  • vue-router

Alternative

No response

Additional context

No response

Validations

[Bug]: build and vue-tsc check type error

Try npm i --save-dev @types/js-cookie if it exists or add a new declaration (.d.ts) file containing declare module 'js-cookie';
import Cookies from 'js-cookie';
TS2307: Cannot find module '@/useRequest/types' or its corresponding type declarations.
import { Service, Options } from '@/useRequest/types';

Maybe typo in docs useRequest/refreshDeps

Describe the bug

When I see useRequest's documentation, in "RefreshDeps" page, I see a remark below.

Only the automatic mode mode, that is, manual is true, depends on the new configuration of swiping the card to have an effect. Manual mode requires users to manage requests themselves.

I think that manual=true may not means automatic mode, it means manual mode. There is are 'mode' in the first sentence.

Maybe it's me misunderstanding.

Steps to reproduce

No response

System Info

macOS Monterey 12.5.1
Chrome 110.0.5481.100 (Official Build) (x86_64)

Used Package Manager

npm

Validations

请教关于useRequest的一个问题

你好,我在写vue3+typescript+element-plus的时候,有个问题。考虑一个场景:当使用el-tab切换的时候,需要调用不同的接口,然后放到下面的el-table中。
想请问下,以前在vue2中,都是定义一个tableData,调用不同的接口可以将数据赋值给tableData,然后给el-table的data,现在vue3中请问是不是每切换一次el-tab,都要执行一下useRequest?
Snipaste_2023-02-15_20-44-18

返回值类型为 readonly

Describe the bug

注意到在此次 commit 中把返回值类型改成了 readonly
eda4900

之前的代码涉及到修改 loading 和重置 data 相关的操作,因此导致升级依赖后报类型异常

想问是出于什么原因进行的修改?如果我需要清除 data 或者调整 loading 状态应该如何实现呢?

Steps to reproduce

No response

System Info

none

Used Package Manager

npm

Validations

VueHooks Plus User 👨🏻‍💻👩🏻‍💻

Discussed in #108

Originally posted by NelsonYong February 17, 2023

Description

🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟

欢迎去知乎回答这个问题:如何评价 VueHooks Plus 这个项目?,说出你的真实开发感受即可。

🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟

iShot_2023-02-17_13 46 26

如果您和您的公司或组织使用了 VueHooks Plus,感谢您的对这个项目的支持!欢迎留下项目名,您的回复将成为维护者、社区用户和观望者的信心来源。

推荐回复格式

- 产品:
- 公司或组织:(如果可以)
- 链接:(如果可以)
- 截图:(如果可以)

We appreciate you support if you or your organization is using VueHooks Plus. You are welcome to leave replies about your product and organization here, which could became the confidence of maintiners, communication and undecided watchers.

Recommended reply format:

- Product:
- Company or Organization: (if any)
- Link: (if any)
- Screenshot: (if any)

useRequest能够支持多请求吗

Describe the bug

这边的理想使用场景是可以处理多请求的情况,像是这样:
const { data: [res1, res2], loading, error } = useRquest([requestFn1, requestF2], options)
主要好处是可以只维护一个loading状态

Steps to reproduce

No response

System Info

no content

Used Package Manager

npm

Validations

请问一下,为什么每个请求都会被触发2次?

在使用 vue-hooks-plus 时,发现每个请求都会被触发2次,这是合理的吗?

function getUsername(): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(666);

      resolve('yong_git');
    }, 1000);
  });
}

const { data } = useRequest(() => {
  console.log('🔥🔥'); // 打印2次
  return getUsername();
});

在线链接:stackblitz

VueHooks Plus User 👨🏻‍💻👩🏻‍💻

Description

🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟

欢迎去知乎回答这个问题:如何评价 VueHooks Plus 这个项目?,说出你的真实开发感受即可。

🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟 🌟

iShot_2023-02-17_13 46 26

如果您和您的公司或组织使用了 VueHooks Plus,感谢您的对这个项目的支持!欢迎留下项目名,您的回复将成为维护者、社区用户和观望者的信心来源。

推荐回复格式

- 产品:
- 公司或组织:(如果可以)
- 链接:(如果可以)
- 截图:(如果可以)

We appreciate you support if you or your organization is using VueHooks Plus. You are welcome to leave replies about your product and organization here, which could became the confidence of maintiners, communication and undecided watchers.

Recommended reply format:

- Product:
- Company or Organization: (if any)
- Link: (if any)
- Screenshot: (if any)

Suggested solution

欢迎 👏 大家贡献维护!
Everyone is welcome 👏 to donate and maintain!

Alternative

No response

Additional context

No response

Validations

useRequest 乐观更新 错误回滚

Description

很多情况下,应用本地的数据更改是一个让人感觉快速的好方法——不需要等待远程数据源。

Suggested solution

具体功能可以参考一下 React 的 SWR请求hooks库中的乐观更新和错误回滚

Alternative

No response

Additional context

No response

Validations

从1.5升级到1.6后出现警告

Describe the bug

升级版本以后使用fetch出现这样的警告
image
查看源码是在这里读取的这个值
image
请问我该怎么避免这个警告

Steps to reproduce

No response

System Info

Windows 
chrome

Used Package Manager

npm

Validations

想理解下 useRequest 中 cancel 是如何使用的

Describe the bug

源码中 onCancel 是什么 需要做什么,
axios 中的 cancelToken 如何能集成在 useRequest中

Steps to reproduce

No response

System Info

Used Package Manager

npm

Validations

Difference / Imporovement compared with vueuse

Hi, thank you for provide such awesome library for vue ecosystem. After reading part of doc and the codebase, I still can't figure out the difference between vueuse.

In personal opinion, the most difference is the api design;
In vueuse

export interface UseToggleOptions<Truthy, Falsy> {
  truthyValue?: MaybeComputedRef<Truthy>
  falsyValue?: MaybeComputedRef<Falsy>
}
export declare function useToggle<Truthy, Falsy, T = Truthy | Falsy>(
  initialValue: Ref<T>,
  options?: UseToggleOptions<Truthy, Falsy>
): (value?: T) => T
export declare function useToggle<
  Truthy = true,
  Falsy = false,
  T = Truthy | Falsy
>(
  initialValue?: T,
  options?: UseToggleOptions<Truthy, Falsy>
): [Ref<T>, (value?: T) => T]

the first argument can be a ref variable or a normal variable.

In vue-hooks-plus,

const [state, { toggle, set, setLeft, setRight }] = useToggle(defaultValue?: boolean);
const [state, { toggle, set, setLeft, setRight }] = useToggle<T>(defaultValue: T);
const [state, { toggle, set, setLeft, setRight }] = useToggle<T, U>(defaultValue: T, reverseValue: U);

the first argument should be a normal variable, and the return value of useToggle is stable as well.

vueuse also make window, document, navigator, location configuable, see _configureable, which can be used in some special cases.

So, it seems that vue-hooks-plus is another "simple" implementation of vueuse in most cases, right?

BTW, I would appliciated it if you can give more descriptive example to respond to #10 (comment)

对 useRequest 的 demo 有疑惑,最终返回的 data 是 undefined

Describe the bug

我根据官方文档中的 useRequest 规范,一步一步走,修改的代码如下,运行 npm run dev 后没有显示 data 的值。
services.ts

import { request } from '../../network/axios'
import { NameType } from './data.d'

export async function getUserInfo() {
  return request<NameType>('https://www.fastmock.site/mock/ca8533cc667844de72db39a6b8ab925a/quiz/id')
}

data.d.ts

export type NameType = {
    desc: string
}

紧接着我 debug 了一下,发现 res 已经得到了数据,但return type显示为 undefined,期待大佬们答疑解惑
image

Steps to reproduce

No response

System Info

Windows 11

Used Package Manager

npm

Validations

打包报错问题

Describe the bug

1.6.0-alpha.7 按需引入vite打包报错,全量引入正常
1.6.0-alpha.2正常
image

Steps to reproduce

No response

System Info

Windows 10,node版本16.18.1

Used Package Manager

npm

Validations

useInfiniteScroll 滚动无法触发

Describe the bug

useInfiniteScroll 滚动无法触发

useInfiniteScroll( async () => { const res = await getMerchantList() console.log(res) return { list: res.records, ...res } }, { target: document.documentElement } )

document.documentElement.scrollTop可以取到值

我滚动的区域是整个页面

Steps to reproduce

No response

System Info

mac m1
google 113.0.5672.63

Used Package Manager

npm

Validations

[useRequest] debounceMaxWait 类型定义错误

Describe the bug

问题

配置项 debounceMaxWait 的类型定义为 Ref<number>,实际上支持 number

image

期望

类型定义正确。

Steps to reproduce

No response

System Info

- `[email protected]`
- `vue@latest`

Used Package Manager

npm

Validations

[useRequest]: 增加初始值设置

原因

通常调用接口后会对返回数据进行空值检验,调用 useRequest 后若直接使用 data 变量在初始时无法改变其 undefined 状态,仅能通过 computed(() => data.value || []) 进行包装处理。

image

期望

希望能增加 initialData 来设置初始的数据状态,便于直接使用 data 变量进行业务处理。

使用useFetchs但是警告

Describe the bug

同样是在setup下使用useFetchs和useRequest,但是useFetchs却报警告
[Vue warn]: onUnmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement. at <SideView visble=true onToggle=fn onResize=fn ... > at <BaseTransition appear=false persisted=false mode=undefined ... > at <Transition enter-active-class="animate__animated animate__bounceInRight" leave-active-class="animate__animated animate__bounceOutRight" > at <App>

[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement. at <SideView visble=true onToggle=fn onResize=fn ... > at <BaseTransition appear=false persisted=false mode=undefined ... > at <Transition enter-active-class="animate__animated animate__bounceInRight" leave-active-class="animate__animated animate__bounceOutRight" > at <App>

Steps to reproduce

No response

System Info

win11 
chrome 109.0.1518.78

Used Package Manager

npm

Validations

Unit Test dynamic statistics

Description

Unit Test dynamic statistics , Displayed on the documentation home page.

Suggested solution

const octokit = require("@octokit/rest")();
const fs = require("fs");

// 设置 GitHub API 认证
octokit.authenticate({
  type: "token",
  token: "YOUR_GITHUB_ACCESS_TOKEN"
});

// 获取仓库中 '.spec.ts' 后缀的文件列表
octokit.repos.getContent({
  owner: "OWNER_USERNAME",
  repo: "REPO_NAME",
  path: "", // 根目录
  recursive: true // 包括所有子目录
}).then(response => {
  const files = response.data.filter(file => file.name.endsWith(".spec.ts"));

  // 读取每个文件并统计 describe 函数数量
  files.forEach(file => {
    octokit.repos.getContent({
      owner: "OWNER_USERNAME",
      repo: "REPO_NAME",
      path: file.path
    }).then(response => {
      const content = Buffer.from(response.data.content, "base64").toString();
      const describeCount = (content.match(/describe\(/g) || []).length;

      console.log(`File: ${file.path}`);
      console.log(`Number of describe functions: ${describeCount}`);
      console.log("------------------------------------");
    }).catch(error => {
      console.error(error);
    });
  });
}).catch(error => {
  console.error(error);
});

Alternative

No response

Additional context

No response

Validations

useSet重置功能有问题

const [set, { add, remove, reset }] = useSet(['hi vue-hooks-plus'])
初始带入默认值,重置的时候直接变成空数组。

在pinia中使用会报错

我将useRequest写在pinia的action中,从别的的地方调用action会警告
[Vue warn]: onUnmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.
请问正确的姿势是什么

[useRequest] Result 类型定义错误

原因

useRequest 的返回中,dataerror 类型定义为 Ref<TData> | undefined,但实际上为 Ref<TData | undefined>,这对开发时造成极大困扰。

image

期望

Result 类型定义正常。

关于打包产物的问题

Describe the bug

由于项目依赖导致打包产物中包含了完整的 lodash,打包体积这块是否可以再优化一下?例如调整为 lodash-es

image

Steps to reproduce

No response

System Info

none

Used Package Manager

npm

Validations

日志代码没有清除

Describe the bug

在代码热更新时触发输出以下内容
image
输出位置位于
image

Steps to reproduce

No response

System Info

其他无关

Used Package Manager

pnpm

Validations

feat: use longPress function

Description

i want proposal a feature that contains pressing state, which allows developers to know if a press is ongoing and the duration of the press. This will provide developers with more flexibility, for instance, they can implement features like canceling with a long press, or decide on different actions based on the duration of the press.

I can submit PR for this feature propose

Suggested solution

listener mouse event to controller pressing state

Alternative

No response

Additional context

No response

Validations

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.