vue-asyncx 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,14 @@
1
- 优雅好用的异步函数/数据管理工具
1
+ 优雅好用的异步函数/数据管理工具 [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/xuyimingwork/vue-asyncx)
2
2
 
3
3
  ![](./docs/compare.png)
4
4
 
5
5
  ## 特性
6
6
 
7
- - 效率+:异步相关样板代码减少40%+
8
- - 可读+:异步操作命名指向明确、风格统一
9
- - 质量+:全 TS 支持 + 100% 单元测试
10
- - 维护+:易于写出符合“干净架构”理念的函数
7
+ - 异步相关样板代码减少40%+
8
+ - 关联状态变量自动命名、风格统一
9
+ - 竟态条件自动处理
10
+ - 完整 TS 类型支持
11
+ - 100% 单元测试覆盖率
11
12
 
12
13
  ## 安装
13
14
 
@@ -139,44 +140,33 @@ const { user } = useAsyncData('user', getUserApi, {
139
140
 
140
141
  `{name}` 数据通常在异步函数调用执行结束时更新,但也可以在异步函数执行过程中更新。
141
142
 
142
- 通过配置 `options.enhanceFirstArgument = true` 实现。
143
-
144
143
  ```js
145
- import { unFirstArgumentEnhanced, useAsyncData } from 'vue-asyncx'
144
+ import { getAsyncDataContext, useAsyncData } from 'vue-asyncx'
146
145
 
147
146
  const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
148
147
 
149
148
  const {
150
149
  progress,
151
150
  queryProgress
152
- } = useAsyncData('progress', async (init?: number) => {
153
- const { getData, updateData } = unFirstArgumentEnhanced(init)
154
- init = unFirstArgumentEnhanced(init).firstArgument
151
+ } = useAsyncData('progress', async (init?: number = 0) => {
152
+ const { getData, updateData } = getAsyncDataContext()
155
153
  // 同步更新为入参 10
156
- updateData(init || 0)
154
+ updateData(init)
157
155
  await wait(100)
158
156
  // 间隔 100ms 后,更新为 50
159
157
  updateData(50)
160
158
  await wait(100)
161
159
  // 间隔 100ms 后,返回 100,本次异步函数完全结束。
162
160
  return 100
163
- }, {
164
- enhanceFirstArgument: true
165
161
  })
166
162
 
167
163
  queryProgress(10)
168
164
  ```
169
165
 
170
- `options.enhanceFirstArgument = true`
171
- - 异步函数的首个参数 `init` 便被转换为 `FirstArgumentEnhanced` 类型,包含 `{ getData, updateData, firstArgument }` 属性。
172
- - 调用 `queryProgress(10)` 时传入的 `10` 在异步函数内部被赋在 `init.firstArgument` 上
173
- - `unFirstArgumentEnhanced(init)` 先解构出 `getData` 和 `updateData`,再将 `init` 重新赋值为传入的 `10`
174
-
175
- > 注意,异步函数的 `init` 不可以直接设置默认值。如:`(init: number = 0) => {}`,可以通过 `unFirstArgumentEnhanced(init, 0)` 设置默认值。
176
-
177
- > 注意,`queryProgress()` 时,`'firstArgument' in unFirstArgumentEnhanced(init)` === `false`,这可以用来区分 `queryProgress()` 与 `queryProgress(undefined)`
166
+ > - `getAsyncDataContext` 只在同步调用时才可获取到正确的上下文
167
+ > - `updateData` 内部已自动处理竟态条件,可以放心调用
178
168
 
179
- ### Debounce
169
+ ### Debounce / Throttle
180
170
 
181
171
  ```ts
182
172
  import { debounce } from 'es-toolkit';
@@ -187,6 +177,7 @@ const {
187
177
  } = useAsyncData('user', getUserApi, {
188
178
  immediate: true,
189
179
  setup(fn) {
180
+ // throttle 配置方式一致
190
181
  return debounce(fn, 500)
191
182
  }
192
183
  })
@@ -194,7 +185,37 @@ const {
194
185
 
195
186
  上面例子中,`queryUser` 等价于 `debounce(fn, 500)`。可以使用任意你喜欢的 `debounce` 函数
196
187
 
197
- > `fn` 是 `useAsyncData` 内部对 `getUserApi` 做的封装。`setup` 返回值为函数类型时,会成为最终返回的 `queryUser`,否则,`queryUser` === `fn`
188
+ > `fn` 是 `useAsyncData` 内部对 `getUserApi` 做的封装。`setup` 返回值为函数类型时,会成为最终返回的 `queryUser`。
189
+
190
+ ### DOM/BOM 事件监听 / 轮询
191
+
192
+ ```ts
193
+ import { debounce } from "es-toolkit"
194
+ import { useEventListener, useIntervalFn } from '@vueuse/core'
195
+
196
+ const {
197
+ user,
198
+ queryUser
199
+ } = useAsyncData('user', getUserApi, {
200
+ immediate: true,
201
+ setup(fn) {
202
+ useEventListener(document, 'visibilitychange', fn)
203
+ useIntervalFn(fn, 1000)
204
+ useEventListener('resize', debounce(fn, 500))
205
+ }
206
+ })
207
+ ```
208
+
209
+ 在 `setup` 中可以像在 vue 组件的 `setup` 中一样注册外部监听器。在上面的例子中,`queryUser` 会:
210
+
211
+ - 立即调用
212
+ - 文档显示隐藏时调用
213
+ - 间隔 1s 轮询
214
+ - 窗口尺寸变化时调用(`debounce` 版本)
215
+
216
+ 注意到:`setup` 没返回函数,此时 `queryUser` === `fn`。
217
+
218
+ > 注意,如果没有使用 `useEventListener` 等自动卸载的工具函数,你需要使用 vue 生命周期钩子手动卸载。
198
219
 
199
220
  ## API
200
221
 
@@ -219,6 +240,5 @@ const {
219
240
  | watchOptions.handlerCreator | 自定义传入 `watch` 的 `handler` | `(fn: Fn) => WatchCallback` | - |
220
241
  | initialData | data 的初始值 | any | undefined |
221
242
  | shallow | 是否使用 `shallowRef` 保存 data,默认使用 `ref` | boolean | false |
222
- | enhanceFirstArgument | 是否强化首个入参 | boolean | false |
223
243
  | setup | 转换函数或执行其它初始化操作 | `(fn: Fn) => ((...args: any) => any) \| void` | - |
224
244
 
@@ -14,10 +14,15 @@ declare type FirstArgumentEnhanced<T = any, D = any> = {
14
14
 
15
15
  declare const FLAG_FIRST_ARGUMENT_ENHANCED = "__va_fae";
16
16
 
17
+ export declare function getAsyncDataContext(): {
18
+ getData: () => any;
19
+ updateData: (v: any) => void;
20
+ };
21
+
17
22
  declare type StringDefaultWhenEmpty<S extends string, D extends string> = S extends '' ? D : S;
18
23
 
19
24
  /**
20
- *
25
+ * @deprecated 已废弃,请使用 getAsyncDataContext
21
26
  * @param arg 首个参数
22
27
  * @param defaultValue 当 arg === undefined 时的默认值
23
28
  * @returns 首个参数解构结果(符合 ts 类型要求)
@@ -37,6 +42,9 @@ export declare function useAsyncData<Data = any, Fn extends (...args: any) => Da
37
42
  declare interface UseAsyncDataOptions<Fn extends (...args: any) => any, Shallow extends boolean> extends UseAsyncOptions<Fn> {
38
43
  initialData?: any;
39
44
  shallow?: Shallow;
45
+ /**
46
+ * @deprecated 已废弃,请使用 getAsyncDataContext
47
+ */
40
48
  enhanceFirstArgument?: boolean;
41
49
  }
42
50
 
@@ -1,191 +1,271 @@
1
- var G = Object.defineProperty, L = Object.defineProperties;
2
- var P = Object.getOwnPropertyDescriptors;
3
- var F = Object.getOwnPropertySymbols;
4
- var O = Object.prototype.hasOwnProperty, b = Object.prototype.propertyIsEnumerable;
5
- var H = (e, t, r) => t in e ? G(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, T = (e, t) => {
6
- for (var r in t || (t = {}))
7
- O.call(t, r) && H(e, r, t[r]);
8
- if (F)
9
- for (var r of F(t))
10
- b.call(t, r) && H(e, r, t[r]);
11
- return e;
12
- }, x = (e, t) => L(e, P(t));
13
- var $ = (e, t) => {
14
- var r = {};
15
- for (var n in e)
16
- O.call(e, n) && t.indexOf(n) < 0 && (r[n] = e[n]);
17
- if (e != null && F)
18
- for (var n of F(e))
19
- t.indexOf(n) < 0 && b.call(e, n) && (r[n] = e[n]);
20
- return r;
21
- };
22
- import { ref as E, computed as l, watch as U, shallowRef as C } from "vue";
23
- function q(e) {
24
- if (!e) return "";
25
- const t = e[0], r = e.slice(1);
26
- return t.toUpperCase() + r;
27
- }
28
- function N() {
29
- const e = E({
30
- // 发起的调用
31
- track: 0,
32
- // 更新的调用
33
- progress: 0,
34
- // 完成的调用,包含报错情况
35
- finished: 0,
36
- // 完成(正常)的调用,不含报错情况
37
- ok: 0
38
- });
39
- function t() {
40
- const r = e.value, n = ++r.track;
41
- return {
42
- progress() {
43
- r.progress >= n || (r.progress = n);
44
- },
45
- finish(u = !1) {
46
- r.finished >= n || (r.finished = n, u || (r.ok = n));
47
- },
48
- expired(u) {
49
- return u ? u === "progress" ? r.progress > n || r.finished >= n : u === "result:ok" ? r.progress > n || r.ok > n : r.progress > n || r.finished > n : r.track > n;
50
- }
51
- };
52
- }
53
- return t.tracking = l(() => e.value.track > 0), t.latest = {
54
- // 已完成
55
- finished: l(() => e.value.track === e.value.finished),
56
- // 已成功
57
- ok: l(() => e.value.track === e.value.ok)
58
- }, t.has = {
59
- // 存在完成
60
- finished: l(() => e.value.finished > 0),
61
- // 存在成功
62
- ok: l(() => e.value.ok > 0),
63
- // 存在更新
64
- progress: l(() => e.value.progress > 0)
65
- }, t;
66
- }
67
- function z(e, t) {
68
- if (typeof t != "function") return e;
69
- try {
70
- const r = t(e);
71
- return typeof r == "function" ? r : e;
72
- } catch (r) {
73
- return e;
74
- }
75
- }
76
- function I(...e) {
77
- var h;
78
- if (!Array.isArray(e) || !e.length) throw TypeError("参数错误:未传递");
79
- const { name: t, fn: r, options: n } = typeof e[0] == "function" ? { name: "method", fn: e[0], options: e[1] } : { name: e[0] || "method", fn: e[1], options: e[2] };
80
- if (typeof t != "string") throw TypeError("参数错误:name");
81
- if (typeof r != "function") throw TypeError("参数错误:fn");
82
- const u = E(!1), p = E(), _ = l(() => {
83
- var a;
84
- return (a = p.value) == null ? void 0 : a[0];
85
- }), k = E(), y = N();
86
- function v(...a) {
87
- const d = y(), A = (c) => {
88
- k.value = void 0, u.value = !0, p.value = c;
89
- }, f = (c, { scene: s }) => {
90
- d.finish(s === "error"), !d.expired() && (s === "error" && (k.value = c), u.value = !1, p.value = void 0);
91
- };
92
- A(a);
93
- try {
94
- const c = r(...a);
95
- return c instanceof Promise ? c.then(
96
- () => f(void 0, { scene: "normal" }),
97
- (s) => f(s, { scene: "error" })
98
- ) : f(void 0, { scene: "normal" }), c;
99
- } catch (c) {
100
- throw f(c, { scene: "error" }), c;
101
- }
102
- }
103
- const m = z(v, n == null ? void 0 : n.setup);
104
- if (n) {
105
- const a = () => {
106
- }, w = Object.assign(
107
- {},
108
- "immediate" in n ? { immediate: n.immediate } : {},
109
- (h = n.watchOptions) != null ? h : {}
110
- ), { handlerCreator: d } = w, A = $(w, ["handlerCreator"]), { watch: f } = n, s = (() => {
111
- const i = () => m();
112
- if (typeof d != "function") return i;
113
- try {
114
- const o = d(m);
115
- return typeof o == "function" ? o : i;
116
- } catch (o) {
117
- return i;
118
- }
119
- })();
120
- U(f != null ? f : a, s, A);
121
- }
122
- return {
123
- [t]: m,
124
- [`${t}Loading`]: u,
125
- [`${t}Arguments`]: p,
126
- [`${t}ArgumentFirst`]: _,
127
- [`${t}Error`]: k
128
- };
129
- }
130
- const R = "__va_fae";
131
- function Q(...e) {
132
- if (!Array.isArray(e) || !e.length) throw TypeError("参数错误:未传递");
133
- const { name: t, fn: r, options: n } = typeof e[0] == "function" ? { name: "data", fn: e[0], options: e[1] } : { name: e[0] || "data", fn: e[1], options: e[2] };
134
- if (typeof t != "string") throw TypeError("参数错误:name");
135
- if (typeof r != "function") throw TypeError("参数错误:fn");
136
- const c = n || {}, { enhanceFirstArgument: u, initialData: p, shallow: _ } = c, k = $(c, ["enhanceFirstArgument", "initialData", "shallow"]), y = _ ? C(p) : E(p), v = C();
137
- function m(s, { track: i, scene: o }) {
138
- o === "update" && i.progress(), !(o === "finish" && i.expired("result:ok")) && (o === "update" && i.expired("progress") || (y.value = s, v.value = i));
139
- }
140
- function h(s, { scene: i, track: o }) {
141
- o.finish(i === "error"), i === "normal" && m(s, { track: o, scene: "finish" });
142
- }
143
- function w(s, {
144
- enhanceFirstArgument: i,
145
- track: o
146
- }) {
147
- if (!i) return s;
148
- const [g, ...j] = s;
149
- return [x(T({
150
- [R]: !0
151
- }, s.length ? { firstArgument: g } : {}), {
152
- getData: () => y.value,
153
- updateData: (D) => (m(D, { track: o, scene: "update" }), D)
154
- }), ...j];
155
- }
156
- const a = N();
157
- function d(...s) {
158
- const i = a();
159
- s = w(s, { enhanceFirstArgument: u, track: i });
160
- try {
161
- const o = r(...s);
162
- return o instanceof Promise ? o.then(
163
- // promise 正常结束
164
- (g) => h(g, { scene: "normal", track: i }),
165
- // promise 出现拒绝
166
- (g) => h(g, { scene: "error", track: i })
167
- ) : h(o, { scene: "normal", track: i }), o;
168
- } catch (o) {
169
- throw h(o, { scene: "error", track: i }), o;
170
- }
171
- }
172
- const A = I(`query${q(t)}`, d, k), f = l(() => a.tracking.value ? v.value ? v.value.expired("result") : a.has.finished.value : !1);
173
- return x(T({}, A), {
174
- [t]: y,
175
- [`${t}Expired`]: f
176
- });
177
- }
178
- function S(e, t) {
179
- if (!M(e)) throw Error("请配置 options.enhanceFirstArgument = true");
180
- const r = e;
181
- return arguments.length === 2 && r.firstArgument === void 0 ? x(T({}, r), { firstArgument: t }) : r;
182
- }
183
- function M(e) {
184
- return typeof e == "object" && !!e && R in e;
185
- }
186
- export {
187
- S as unFirstArgumentEnhanced,
188
- I as useAsync,
189
- Q as useAsyncData,
190
- I as useAsyncFunction
1
+ import { computed, ref, shallowRef, watch } from "vue";
2
+ function upperFirst(e) {
3
+ if (!e) return "";
4
+ let a = e[0], o = e.slice(1);
5
+ return a.toUpperCase() + o;
6
+ }
7
+ function createFunctionTracker() {
8
+ let o = ref({
9
+ track: 0,
10
+ progress: 0,
11
+ finished: 0,
12
+ ok: 0
13
+ });
14
+ function s() {
15
+ let e = o.value, a = ++e.track;
16
+ return {
17
+ progress() {
18
+ e.progress >= a || (e.progress = a);
19
+ },
20
+ finish(o = !1) {
21
+ e.finished >= a || (e.finished = a, o || (e.ok = a));
22
+ },
23
+ expired(o) {
24
+ return o ? o === "progress" ? e.progress > a || e.finished >= a : o === "result:ok" ? e.progress > a || e.ok > a : e.progress > a || e.finished > a : e.track > a;
25
+ }
26
+ };
27
+ }
28
+ return s.tracking = computed(() => o.value.track > 0), s.latest = {
29
+ finished: computed(() => o.value.track === o.value.finished),
30
+ ok: computed(() => o.value.track === o.value.ok)
31
+ }, s.has = {
32
+ finished: computed(() => o.value.finished > 0),
33
+ ok: computed(() => o.value.ok > 0),
34
+ progress: computed(() => o.value.progress > 0)
35
+ }, s;
36
+ }
37
+ function _objectWithoutPropertiesLoose(e, a) {
38
+ if (e == null) return {};
39
+ var o = {};
40
+ for (var s in e) if ({}.hasOwnProperty.call(e, s)) {
41
+ if (a.includes(s)) continue;
42
+ o[s] = e[s];
43
+ }
44
+ return o;
45
+ }
46
+ function _objectWithoutProperties(e, a) {
47
+ if (e == null) return {};
48
+ var o, s, c = _objectWithoutPropertiesLoose(e, a);
49
+ if (Object.getOwnPropertySymbols) {
50
+ var l = Object.getOwnPropertySymbols(e);
51
+ for (s = 0; s < l.length; s++) o = l[s], a.includes(o) || {}.propertyIsEnumerable.call(e, o) && (c[o] = e[o]);
52
+ }
53
+ return c;
54
+ }
55
+ var _excluded$1 = ["handlerCreator"];
56
+ function getFunction(e, a) {
57
+ if (typeof a != "function") return e;
58
+ try {
59
+ let o = a(e);
60
+ return typeof o == "function" ? o : e;
61
+ } catch (a) {
62
+ return e;
63
+ }
64
+ }
65
+ function useAsync(...o) {
66
+ if (!Array.isArray(o) || !o.length) throw TypeError("参数错误:未传递");
67
+ let { name: c, fn: u, options: p } = typeof o[0] == "function" ? {
68
+ name: "method",
69
+ fn: o[0],
70
+ options: o[1]
71
+ } : {
72
+ name: o[0] || "method",
73
+ fn: o[1],
74
+ options: o[2]
75
+ };
76
+ if (typeof c != "string") throw TypeError("参数错误:name");
77
+ if (typeof u != "function") throw TypeError("参数错误:fn");
78
+ let m = ref(!1), h = ref(), g = computed(() => {
79
+ var e;
80
+ return (e = h.value) == null ? void 0 : e[0];
81
+ }), _ = ref(), v = createFunctionTracker();
82
+ function y(...e) {
83
+ let a = v(), o = (e) => {
84
+ _.value = void 0, m.value = !0, h.value = e;
85
+ }, s = (e, { scene: o }) => {
86
+ a.finish(o === "error"), !a.expired() && (o === "error" && (_.value = e), m.value = !1, h.value = void 0);
87
+ };
88
+ o(e);
89
+ try {
90
+ let a = u(...e);
91
+ return a instanceof Promise ? a.then(() => s(void 0, { scene: "normal" }), (e) => s(e, { scene: "error" })) : s(void 0, { scene: "normal" }), a;
92
+ } catch (e) {
93
+ throw s(e, { scene: "error" }), e;
94
+ }
95
+ }
96
+ let b = getFunction(y, p == null ? void 0 : p.setup);
97
+ if (p) {
98
+ var x;
99
+ let e = () => {}, a = Object.assign({}, "immediate" in p ? { immediate: p.immediate } : {}, (x = p.watchOptions) == null ? {} : x), { handlerCreator: o } = a, c = _objectWithoutProperties(a, _excluded$1), { watch: l } = p, u = (() => {
100
+ let e = () => b();
101
+ if (typeof o != "function") return e;
102
+ try {
103
+ let a = o(b);
104
+ return typeof a == "function" ? a : e;
105
+ } catch (a) {
106
+ return e;
107
+ }
108
+ })();
109
+ watch(l == null ? e : l, u, c);
110
+ }
111
+ return {
112
+ [c]: b,
113
+ [`${c}Loading`]: m,
114
+ [`${c}Arguments`]: h,
115
+ [`${c}ArgumentFirst`]: g,
116
+ [`${c}Error`]: _
117
+ };
118
+ }
119
+ var currentContextGetter = () => {
120
+ throw Error("[vue-asyncx] getAsyncDataContext 必须在 useAsyncData 的封装函数内调用");
191
121
  };
122
+ function prepareAsyncDataContext(e) {
123
+ let a = currentContextGetter, o = () => e;
124
+ currentContextGetter = o;
125
+ function s() {
126
+ if (o !== currentContextGetter) throw Error("[vue-asyncx] 嵌套 AsyncDataContext 必须顺序恢复");
127
+ currentContextGetter = a;
128
+ }
129
+ return s;
130
+ }
131
+ function getAsyncDataContext() {
132
+ return currentContextGetter();
133
+ }
134
+ function _typeof(e) {
135
+ "@babel/helpers - typeof";
136
+ return _typeof = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
137
+ return typeof e;
138
+ } : function(e) {
139
+ return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
140
+ }, _typeof(e);
141
+ }
142
+ function toPrimitive(e, a) {
143
+ if (_typeof(e) != "object" || !e) return e;
144
+ var o = e[Symbol.toPrimitive];
145
+ if (o !== void 0) {
146
+ var s = o.call(e, a || "default");
147
+ if (_typeof(s) != "object") return s;
148
+ throw TypeError("@@toPrimitive must return a primitive value.");
149
+ }
150
+ return (a === "string" ? String : Number)(e);
151
+ }
152
+ function toPropertyKey(e) {
153
+ var a = toPrimitive(e, "string");
154
+ return _typeof(a) == "symbol" ? a : a + "";
155
+ }
156
+ function _defineProperty(e, a, o) {
157
+ return (a = toPropertyKey(a)) in e ? Object.defineProperty(e, a, {
158
+ value: o,
159
+ enumerable: !0,
160
+ configurable: !0,
161
+ writable: !0
162
+ }) : e[a] = o, e;
163
+ }
164
+ function ownKeys(e, a) {
165
+ var o = Object.keys(e);
166
+ if (Object.getOwnPropertySymbols) {
167
+ var s = Object.getOwnPropertySymbols(e);
168
+ a && (s = s.filter(function(a) {
169
+ return Object.getOwnPropertyDescriptor(e, a).enumerable;
170
+ })), o.push.apply(o, s);
171
+ }
172
+ return o;
173
+ }
174
+ function _objectSpread2(e) {
175
+ for (var a = 1; a < arguments.length; a++) {
176
+ var o = arguments[a] == null ? {} : arguments[a];
177
+ a % 2 ? ownKeys(Object(o), !0).forEach(function(a) {
178
+ _defineProperty(e, a, o[a]);
179
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(o)) : ownKeys(Object(o)).forEach(function(a) {
180
+ Object.defineProperty(e, a, Object.getOwnPropertyDescriptor(o, a));
181
+ });
182
+ }
183
+ return e;
184
+ }
185
+ var _excluded = [
186
+ "enhanceFirstArgument",
187
+ "initialData",
188
+ "shallow"
189
+ ], FLAG_FIRST_ARGUMENT_ENHANCED = "__va_fae";
190
+ function useAsyncData(...s) {
191
+ if (!Array.isArray(s) || !s.length) throw TypeError("参数错误:未传递");
192
+ let { name: u, fn: d, options: f } = typeof s[0] == "function" ? {
193
+ name: "data",
194
+ fn: s[0],
195
+ options: s[1]
196
+ } : {
197
+ name: s[0] || "data",
198
+ fn: s[1],
199
+ options: s[2]
200
+ };
201
+ if (typeof u != "string") throw TypeError("参数错误:name");
202
+ if (typeof d != "function") throw TypeError("参数错误:fn");
203
+ let m = f || {}, { enhanceFirstArgument: g, initialData: _, shallow: v } = m, y = _objectWithoutProperties(m, _excluded), b = v ? shallowRef(_) : ref(_), x = shallowRef();
204
+ function S(e, { track: a, scene: o, error: s = !1 }) {
205
+ o === "update" && a.progress(), !(o === "update" && a.expired("progress")) && (o === "finish" && a.finish(s), !(o === "finish" && a.expired("result:ok")) && (o === "finish" && s || (b.value = e, x.value = a)));
206
+ }
207
+ function C(e, { scene: a, track: o }) {
208
+ S(e, {
209
+ track: o,
210
+ scene: "finish",
211
+ error: a === "error"
212
+ });
213
+ }
214
+ function w({ track: e }) {
215
+ return {
216
+ getData: () => b.value,
217
+ updateData: (a) => (S(a, {
218
+ track: e,
219
+ scene: "update"
220
+ }), a)
221
+ };
222
+ }
223
+ function T(e, { enhanceFirstArgument: a, track: o }) {
224
+ if (!a) return e;
225
+ let [s, ...c] = e;
226
+ return [_objectSpread2(_objectSpread2({ [FLAG_FIRST_ARGUMENT_ENHANCED]: !0 }, e.length ? { firstArgument: s } : {}), w({ track: o })), ...c];
227
+ }
228
+ let E = createFunctionTracker();
229
+ function D(...e) {
230
+ let a = E();
231
+ e = T(e, {
232
+ enhanceFirstArgument: g,
233
+ track: a
234
+ });
235
+ let o = prepareAsyncDataContext(w({ track: a }));
236
+ try {
237
+ let o = d(...e);
238
+ return o instanceof Promise ? o.then((e) => C(e, {
239
+ scene: "normal",
240
+ track: a
241
+ }), (e) => C(e, {
242
+ scene: "error",
243
+ track: a
244
+ })) : C(o, {
245
+ scene: "normal",
246
+ track: a
247
+ }), o;
248
+ } catch (e) {
249
+ throw C(e, {
250
+ scene: "error",
251
+ track: a
252
+ }), e;
253
+ } finally {
254
+ o();
255
+ }
256
+ }
257
+ let O = useAsync(`query${upperFirst(u)}`, D, y), k = computed(() => E.tracking.value ? x.value ? x.value.expired("result") : E.has.finished.value : !1);
258
+ return _objectSpread2(_objectSpread2({}, O), {}, {
259
+ [u]: b,
260
+ [`${u}Expired`]: k
261
+ });
262
+ }
263
+ function unFirstArgumentEnhanced(e, a) {
264
+ if (!isFirstArgumentEnhanced(e)) throw Error("请配置 options.enhanceFirstArgument = true");
265
+ let o = e;
266
+ return arguments.length === 2 && o.firstArgument === void 0 ? _objectSpread2(_objectSpread2({}, o), {}, { firstArgument: a }) : o;
267
+ }
268
+ function isFirstArgumentEnhanced(e) {
269
+ return typeof e == "object" && !!e && FLAG_FIRST_ARGUMENT_ENHANCED in e;
270
+ }
271
+ export { getAsyncDataContext, unFirstArgumentEnhanced, useAsync, useAsync as useAsyncFunction, useAsyncData };
@@ -1 +1 @@
1
- (function(r,t){typeof exports=="object"&&typeof module!="undefined"?t(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],t):(r=typeof globalThis!="undefined"?globalThis:r||self,t(r.VueAsyncx={},r.Vue))})(this,function(r,t){"use strict";var S=Object.defineProperty,U=Object.defineProperties;var V=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var R=(r,t,f)=>t in r?S(r,t,{enumerable:!0,configurable:!0,writable:!0,value:f}):r[t]=f,_=(r,t)=>{for(var f in t||(t={}))C.call(t,f)&&R(r,f,t[f]);if(x)for(var f of x(t))N.call(t,f)&&R(r,f,t[f]);return r},D=(r,t)=>U(r,V(t));var O=(r,t)=>{var f={};for(var d in r)C.call(r,d)&&t.indexOf(d)<0&&(f[d]=r[d]);if(r!=null&&x)for(var d of x(r))t.indexOf(d)<0&&N.call(r,d)&&(f[d]=r[d]);return f};function f(e){if(!e)return"";const o=e[0],n=e.slice(1);return o.toUpperCase()+n}function d(){const e=t.ref({track:0,progress:0,finished:0,ok:0});function o(){const n=e.value,i=++n.track;return{progress(){n.progress>=i||(n.progress=i)},finish(p=!1){n.finished>=i||(n.finished=i,p||(n.ok=i))},expired(p){return p?p==="progress"?n.progress>i||n.finished>=i:p==="result:ok"?n.progress>i||n.ok>i:n.progress>i||n.finished>i:n.track>i}}}return o.tracking=t.computed(()=>e.value.track>0),o.latest={finished:t.computed(()=>e.value.track===e.value.finished),ok:t.computed(()=>e.value.track===e.value.ok)},o.has={finished:t.computed(()=>e.value.finished>0),ok:t.computed(()=>e.value.ok>0),progress:t.computed(()=>e.value.progress>0)},o}function P(e,o){if(typeof o!="function")return e;try{const n=o(e);return typeof n=="function"?n:e}catch(n){return e}}function $(...e){var y;if(!Array.isArray(e)||!e.length)throw TypeError("参数错误:未传递");const{name:o,fn:n,options:i}=typeof e[0]=="function"?{name:"method",fn:e[0],options:e[1]}:{name:e[0]||"method",fn:e[1],options:e[2]};if(typeof o!="string")throw TypeError("参数错误:name");if(typeof n!="function")throw TypeError("参数错误:fn");const p=t.ref(!1),m=t.ref(),b=t.computed(()=>{var l;return(l=m.value)==null?void 0:l[0]}),g=t.ref(),E=d();function w(...l){const k=E(),v=a=>{g.value=void 0,p.value=!0,m.value=a},h=(a,{scene:u})=>{k.finish(u==="error"),!k.expired()&&(u==="error"&&(g.value=a),p.value=!1,m.value=void 0)};v(l);try{const a=n(...l);return a instanceof Promise?a.then(()=>h(void 0,{scene:"normal"}),u=>h(u,{scene:"error"})):h(void 0,{scene:"normal"}),a}catch(a){throw h(a,{scene:"error"}),a}}const A=P(w,i==null?void 0:i.setup);if(i){const l=()=>{},T=Object.assign({},"immediate"in i?{immediate:i.immediate}:{},(y=i.watchOptions)!=null?y:{}),{handlerCreator:k}=T,v=O(T,["handlerCreator"]),{watch:h}=i,u=(()=>{const c=()=>A();if(typeof k!="function")return c;try{const s=k(A);return typeof s=="function"?s:c}catch(s){return c}})();t.watch(h!=null?h:l,u,v)}return{[o]:A,[`${o}Loading`]:p,[`${o}Arguments`]:m,[`${o}ArgumentFirst`]:b,[`${o}Error`]:g}}const j="__va_fae";function q(...e){if(!Array.isArray(e)||!e.length)throw TypeError("参数错误:未传递");const{name:o,fn:n,options:i}=typeof e[0]=="function"?{name:"data",fn:e[0],options:e[1]}:{name:e[0]||"data",fn:e[1],options:e[2]};if(typeof o!="string")throw TypeError("参数错误:name");if(typeof n!="function")throw TypeError("参数错误:fn");const a=i||{},{enhanceFirstArgument:p,initialData:m,shallow:b}=a,g=O(a,["enhanceFirstArgument","initialData","shallow"]),E=b?t.shallowRef(m):t.ref(m),w=t.shallowRef();function A(u,{track:c,scene:s}){s==="update"&&c.progress(),!(s==="finish"&&c.expired("result:ok"))&&(s==="update"&&c.expired("progress")||(E.value=u,w.value=c))}function y(u,{scene:c,track:s}){s.finish(c==="error"),c==="normal"&&A(u,{track:s,scene:"finish"})}function T(u,{enhanceFirstArgument:c,track:s}){if(!c)return u;const[F,...M]=u;return[D(_({[j]:!0},u.length?{firstArgument:F}:{}),{getData:()=>E.value,updateData:H=>(A(H,{track:s,scene:"update"}),H)}),...M]}const l=d();function k(...u){const c=l();u=T(u,{enhanceFirstArgument:p,track:c});try{const s=n(...u);return s instanceof Promise?s.then(F=>y(F,{scene:"normal",track:c}),F=>y(F,{scene:"error",track:c})):y(s,{scene:"normal",track:c}),s}catch(s){throw y(s,{scene:"error",track:c}),s}}const v=$(`query${f(o)}`,k,g),h=t.computed(()=>l.tracking.value?w.value?w.value.expired("result"):l.has.finished.value:!1);return D(_({},v),{[o]:E,[`${o}Expired`]:h})}function G(e,o){if(!L(e))throw Error("请配置 options.enhanceFirstArgument = true");const n=e;return arguments.length===2&&n.firstArgument===void 0?D(_({},n),{firstArgument:o}):n}function L(e){return typeof e=="object"&&!!e&&j in e}r.unFirstArgumentEnhanced=G,r.useAsync=$,r.useAsyncData=q,r.useAsyncFunction=$,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`vue`)):typeof define==`function`&&define.amd?define([`exports`,`vue`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.VueAsyncx={},e.Vue))})(this,function(e,t){function n(e){if(!e)return``;let t=e[0],n=e.slice(1);return t.toUpperCase()+n}function r(){let e=(0,t.ref)({track:0,progress:0,finished:0,ok:0});function n(){let t=e.value,n=++t.track;return{progress(){t.progress>=n||(t.progress=n)},finish(e=!1){t.finished>=n||(t.finished=n,e||(t.ok=n))},expired(e){return e?e===`progress`?t.progress>n||t.finished>=n:e===`result:ok`?t.progress>n||t.ok>n:t.progress>n||t.finished>n:t.track>n}}}return n.tracking=(0,t.computed)(()=>e.value.track>0),n.latest={finished:(0,t.computed)(()=>e.value.track===e.value.finished),ok:(0,t.computed)(()=>e.value.track===e.value.ok)},n.has={finished:(0,t.computed)(()=>e.value.finished>0),ok:(0,t.computed)(()=>e.value.ok>0),progress:(0,t.computed)(()=>e.value.progress>0)},n}function i(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function a(e,t){if(e==null)return{};var n,r,a=i(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var o=[`handlerCreator`];function s(e,t){if(typeof t!=`function`)return e;try{let n=t(e);return typeof n==`function`?n:e}catch(t){return e}}function c(...e){if(!Array.isArray(e)||!e.length)throw TypeError(`参数错误:未传递`);let{name:n,fn:i,options:c}=typeof e[0]==`function`?{name:`method`,fn:e[0],options:e[1]}:{name:e[0]||`method`,fn:e[1],options:e[2]};if(typeof n!=`string`)throw TypeError(`参数错误:name`);if(typeof i!=`function`)throw TypeError(`参数错误:fn`);let l=(0,t.ref)(!1),u=(0,t.ref)(),d=(0,t.computed)(()=>{var e;return(e=u.value)==null?void 0:e[0]}),f=(0,t.ref)(),p=r();function m(...e){let t=p(),n=e=>{f.value=void 0,l.value=!0,u.value=e},r=(e,{scene:n})=>{t.finish(n===`error`),!t.expired()&&(n===`error`&&(f.value=e),l.value=!1,u.value=void 0)};n(e);try{let t=i(...e);return t instanceof Promise?t.then(()=>r(void 0,{scene:`normal`}),e=>r(e,{scene:`error`})):r(void 0,{scene:`normal`}),t}catch(e){throw r(e,{scene:`error`}),e}}let h=s(m,c==null?void 0:c.setup);if(c){var g;let e=()=>{},n=Object.assign({},`immediate`in c?{immediate:c.immediate}:{},(g=c.watchOptions)==null?{}:g),{handlerCreator:r}=n,i=a(n,o),{watch:s}=c,l=(()=>{let e=()=>h();if(typeof r!=`function`)return e;try{let t=r(h);return typeof t==`function`?t:e}catch(t){return e}})();(0,t.watch)(s==null?e:s,l,i)}return{[n]:h,[`${n}Loading`]:l,[`${n}Arguments`]:u,[`${n}ArgumentFirst`]:d,[`${n}Error`]:f}}var l=()=>{throw Error(`[vue-asyncx] getAsyncDataContext 必须在 useAsyncData 的封装函数内调用`)};function u(e){let t=l,n=()=>e;l=n;function r(){if(n!==l)throw Error(`[vue-asyncx] 嵌套 AsyncDataContext 必须顺序恢复`);l=t}return r}function d(){return l()}function f(e){"@babel/helpers - typeof";return f=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},f(e)}function p(e,t){if(f(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(f(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function m(e){var t=p(e,`string`);return f(t)==`symbol`?t:t+``}function h(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function _(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?g(Object(n),!0).forEach(function(t){h(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var v=[`enhanceFirstArgument`,`initialData`,`shallow`],y=`__va_fae`;function b(...e){if(!Array.isArray(e)||!e.length)throw TypeError(`参数错误:未传递`);let{name:i,fn:o,options:s}=typeof e[0]==`function`?{name:`data`,fn:e[0],options:e[1]}:{name:e[0]||`data`,fn:e[1],options:e[2]};if(typeof i!=`string`)throw TypeError(`参数错误:name`);if(typeof o!=`function`)throw TypeError(`参数错误:fn`);let l=s||{},{enhanceFirstArgument:d,initialData:f,shallow:p}=l,m=a(l,v),h=p?(0,t.shallowRef)(f):(0,t.ref)(f),g=(0,t.shallowRef)();function b(e,{track:t,scene:n,error:r=!1}){n===`update`&&t.progress(),!(n===`update`&&t.expired(`progress`))&&(n===`finish`&&t.finish(r),!(n===`finish`&&t.expired(`result:ok`))&&(n===`finish`&&r||(h.value=e,g.value=t)))}function x(e,{scene:t,track:n}){b(e,{track:n,scene:`finish`,error:t===`error`})}function S({track:e}){return{getData:()=>h.value,updateData:t=>(b(t,{track:e,scene:`update`}),t)}}function C(e,{enhanceFirstArgument:t,track:n}){if(!t)return e;let[r,...i]=e;return[_(_({[y]:!0},e.length?{firstArgument:r}:{}),S({track:n})),...i]}let w=r();function T(...e){let t=w();e=C(e,{enhanceFirstArgument:d,track:t});let n=u(S({track:t}));try{let n=o(...e);return n instanceof Promise?n.then(e=>x(e,{scene:`normal`,track:t}),e=>x(e,{scene:`error`,track:t})):x(n,{scene:`normal`,track:t}),n}catch(e){throw x(e,{scene:`error`,track:t}),e}finally{n()}}let E=c(`query${n(i)}`,T,m),D=(0,t.computed)(()=>w.tracking.value?g.value?g.value.expired(`result`):w.has.finished.value:!1);return _(_({},E),{},{[i]:h,[`${i}Expired`]:D})}function x(e,t){if(!S(e))throw Error(`请配置 options.enhanceFirstArgument = true`);let n=e;return arguments.length===2&&n.firstArgument===void 0?_(_({},n),{},{firstArgument:t}):n}function S(e){return typeof e==`object`&&!!e&&y in e}e.getAsyncDataContext=d,e.unFirstArgumentEnhanced=x,e.useAsync=c,e.useAsyncFunction=c,e.useAsyncData=b});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-asyncx",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "dist/vue-asyncx.d.ts",
@@ -30,14 +30,14 @@
30
30
  "url": "git+https://github.com/xuyimingwork/vue-asyncx.git"
31
31
  },
32
32
  "devDependencies": {
33
- "@types/node": "^20.14.11",
34
- "@vitest/coverage-v8": "^2.0.4",
33
+ "@types/node": "^22.19.1",
34
+ "@vitest/coverage-v8": "^4.0.14",
35
+ "@vueuse/core": "^14.0.0",
35
36
  "es-toolkit": "^1.42.0",
36
37
  "jsdom": "^24.1.1",
37
- "typescript": "^5.5.4",
38
- "vite": "^5.3.4",
39
- "vite-plugin-dts": "4.0.0-beta.1",
40
- "vitest": "^2.0.4"
38
+ "vite": "^6.4.1",
39
+ "vite-plugin-dts": "^4.5.4",
40
+ "vitest": "^4.0.14"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "vue": ">=3.0.0"