@wangyuanlin/vue-smart-request-plugin
v0.1.0
Published
A practical Vue request management plugin with dedupe, cache, retry, timeout and global busy states.
Downloads
47
Maintainers
Readme
@linking/vue-smart-request-plugin
一个更偏工程化的 Vue 请求管理插件,解决项目里常见的异步请求痛点:
- 相同接口并发时重复请求(自动去重)
- 页面切换后请求还在跑(支持取消)
- 重试、超时、缓存逻辑分散在业务代码里(统一收敛)
- 全局 loading 和按钮禁用状态不好管理(
activeCount+v-sr-busy)
支持 Vue 2.7+ / Vue 3(基于 vue-demi)。
安装
npm i @linking/vue-smart-request-plugin快速开始
Vue 3
import { createApp } from 'vue';
import App from './App.vue';
import { createSmartRequestPlugin } from '@linking/vue-smart-request-plugin';
const app = createApp(App);
app.use(
createSmartRequestPlugin({
request: {
dedupe: true,
cache: true,
ttl: 30_000,
retries: 1,
timeout: 12_000
}
})
);
app.mount('#app');Vue 2
import Vue from 'vue';
import { createSmartRequestPlugin } from '@linking/vue-smart-request-plugin';
Vue.use(createSmartRequestPlugin());使用方式
1) useAsyncQuery
import { ref } from 'vue';
import { useAsyncQuery } from '@linking/vue-smart-request-plugin';
const userId = ref('1001');
const query = useAsyncQuery(
() => `user:${userId.value}`,
async ({ signal }) => {
const res = await fetch(`/api/user/${userId.value}`, { signal });
return res.json();
},
{
immediate: true,
cache: true,
ttl: 60_000,
retries: 2
}
);返回值:
data/error/loading/status/updatedAtrun/refresh/invalidate/cancel
2) useAsyncMutation
import { useAsyncMutation } from '@linking/vue-smart-request-plugin';
const mutation = useAsyncMutation(
async (payload: { title: string }, { signal }) => {
const res = await fetch('/api/post', {
method: 'POST',
signal,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
return res.json();
},
{
mutationKey: 'post:create',
invalidateKeys: ['post:list']
}
);返回值:
data/error/loading/status/updatedAt/variablesmutate/mutateAsync/cancel/reset
3) 全局工具 $sr
this.$sr.request('post:list', async ({ signal }) => {
const res = await fetch('/api/post/list', { signal });
return res.json();
});
const isBusy = this.$sr.isLoading.value;4) 指令 v-sr-busy
<button v-sr-busy="loading">提交</button>
<button
v-sr-busy="{
loading,
loadingText: '提交中...',
idleText: '提交',
className: 'my-busy'
}"
>
提交
</button>核心 API(client)
插件内部使用 SmartRequestClient,也可以直接使用:
execute(key, fetcher, options)prefetch(key, fetcher, options)cancel(key)invalidate(key | predicate)clearCache()getCachedData(key)activeCount/isLoading
发布前检查
npm run typecheck
npm run test
npm run build