@banmao/hooks 0.0.3 → 0.0.5

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,5 +1,38 @@
1
- # Vue 3 + TypeScript + Vite
1
+ # @banmao/hooks
2
2
 
3
- This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
3
+ 这是一个基于 Vue Composition API 的自定义 Hooks 库,旨在提高开发效率并简化复杂的状态管理和逻辑处理。
4
4
 
5
- Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
5
+ ## 特性
6
+
7
+ - 提供多种实用的 Vue Composition API Hooks
8
+ - 易于集成到 Vue 3 项目中
9
+ - 支持 TypeScript,具有完善的类型定义
10
+
11
+ ## 安装
12
+
13
+ 使用 pnpm 或 yarn 安装:
14
+
15
+ ```bash
16
+ pnpm install @banmao/hooks
17
+ # 或者
18
+ yarn add @banmao/hooks
19
+
20
+ ```vue
21
+ import { useCustomHook } from '@banmao/hooks';
22
+ <script setup>
23
+ defineComponent({
24
+ setup() {
25
+ const { value, setValue } = useCustomHook();
26
+
27
+ return {
28
+ value,
29
+ setValue,
30
+ };
31
+ },
32
+ });
33
+ </script>
34
+
35
+ <template>
36
+ <!-- element -->
37
+ </template>
38
+ ```
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  export * from './useExportRemoteFile';
2
2
  export * from './useList';
3
+ export * from './useTableHeight';
4
+ export * from './useAsyncData';
package/dist/index.js CHANGED
@@ -1,389 +1,4 @@
1
- import { inject as X, ref as J, computed as ee, onMounted as te } from "vue";
2
- function ne(l) {
3
- return l && l.__esModule && Object.prototype.hasOwnProperty.call(l, "default") ? l.default : l;
4
- }
5
- var Z = { exports: {} }, re = Z.exports, G;
6
- function se() {
7
- return G || (G = 1, function(l, O) {
8
- (function(D, b) {
9
- l.exports = b();
10
- })(re, function() {
11
- var D = 1e3, b = 6e4, g = 36e5, E = "millisecond", L = "second", _ = "minute", $ = "hour", v = "day", H = "week", p = "month", T = "quarter", x = "year", C = "date", P = "Invalid Date", B = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, Q = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, c = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(s) {
12
- var n = ["th", "st", "nd", "rd"], e = s % 100;
13
- return "[" + s + (n[(e - 20) % 10] || n[e] || n[0]) + "]";
14
- } }, w = function(s, n, e) {
15
- var r = String(s);
16
- return !r || r.length >= n ? s : "" + Array(n + 1 - r.length).join(e) + s;
17
- }, j = { s: w, z: function(s) {
18
- var n = -s.utcOffset(), e = Math.abs(n), r = Math.floor(e / 60), t = e % 60;
19
- return (n <= 0 ? "+" : "-") + w(r, 2, "0") + ":" + w(t, 2, "0");
20
- }, m: function s(n, e) {
21
- if (n.date() < e.date()) return -s(e, n);
22
- var r = 12 * (e.year() - n.year()) + (e.month() - n.month()), t = n.clone().add(r, p), a = e - t < 0, i = n.clone().add(r + (a ? -1 : 1), p);
23
- return +(-(r + (e - t) / (a ? t - i : i - t)) || 0);
24
- }, a: function(s) {
25
- return s < 0 ? Math.ceil(s) || 0 : Math.floor(s);
26
- }, p: function(s) {
27
- return { M: p, y: x, w: H, d: v, D: C, h: $, m: _, s: L, ms: E, Q: T }[s] || String(s || "").toLowerCase().replace(/s$/, "");
28
- }, u: function(s) {
29
- return s === void 0;
30
- } }, S = "en", k = {};
31
- k[S] = c;
32
- var R = "$isDayjsObject", W = function(s) {
33
- return s instanceof q || !(!s || !s[R]);
34
- }, U = function s(n, e, r) {
35
- var t;
36
- if (!n) return S;
37
- if (typeof n == "string") {
38
- var a = n.toLowerCase();
39
- k[a] && (t = a), e && (k[a] = e, t = a);
40
- var i = n.split("-");
41
- if (!t && i.length > 1) return s(i[0]);
42
- } else {
43
- var o = n.name;
44
- k[o] = n, t = o;
45
- }
46
- return !r && t && (S = t), t || !r && S;
47
- }, d = function(s, n) {
48
- if (W(s)) return s.clone();
49
- var e = typeof n == "object" ? n : {};
50
- return e.date = s, e.args = arguments, new q(e);
51
- }, u = j;
52
- u.l = U, u.i = W, u.w = function(s, n) {
53
- return d(s, { locale: n.$L, utc: n.$u, x: n.$x, $offset: n.$offset });
54
- };
55
- var q = function() {
56
- function s(e) {
57
- this.$L = U(e.locale, null, !0), this.parse(e), this.$x = this.$x || e.x || {}, this[R] = !0;
58
- }
59
- var n = s.prototype;
60
- return n.parse = function(e) {
61
- this.$d = function(r) {
62
- var t = r.date, a = r.utc;
63
- if (t === null) return /* @__PURE__ */ new Date(NaN);
64
- if (u.u(t)) return /* @__PURE__ */ new Date();
65
- if (t instanceof Date) return new Date(t);
66
- if (typeof t == "string" && !/Z$/i.test(t)) {
67
- var i = t.match(B);
68
- if (i) {
69
- var o = i[2] - 1 || 0, f = (i[7] || "0").substring(0, 3);
70
- return a ? new Date(Date.UTC(i[1], o, i[3] || 1, i[4] || 0, i[5] || 0, i[6] || 0, f)) : new Date(i[1], o, i[3] || 1, i[4] || 0, i[5] || 0, i[6] || 0, f);
71
- }
72
- }
73
- return new Date(t);
74
- }(e), this.init();
75
- }, n.init = function() {
76
- var e = this.$d;
77
- this.$y = e.getFullYear(), this.$M = e.getMonth(), this.$D = e.getDate(), this.$W = e.getDay(), this.$H = e.getHours(), this.$m = e.getMinutes(), this.$s = e.getSeconds(), this.$ms = e.getMilliseconds();
78
- }, n.$utils = function() {
79
- return u;
80
- }, n.isValid = function() {
81
- return this.$d.toString() !== P;
82
- }, n.isSame = function(e, r) {
83
- var t = d(e);
84
- return this.startOf(r) <= t && t <= this.endOf(r);
85
- }, n.isAfter = function(e, r) {
86
- return d(e) < this.startOf(r);
87
- }, n.isBefore = function(e, r) {
88
- return this.endOf(r) < d(e);
89
- }, n.$g = function(e, r, t) {
90
- return u.u(e) ? this[r] : this.set(t, e);
91
- }, n.unix = function() {
92
- return Math.floor(this.valueOf() / 1e3);
93
- }, n.valueOf = function() {
94
- return this.$d.getTime();
95
- }, n.startOf = function(e, r) {
96
- var t = this, a = !!u.u(r) || r, i = u.p(e), o = function(A, y) {
97
- var Y = u.w(t.$u ? Date.UTC(t.$y, y, A) : new Date(t.$y, y, A), t);
98
- return a ? Y : Y.endOf(v);
99
- }, f = function(A, y) {
100
- return u.w(t.toDate()[A].apply(t.toDate("s"), (a ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(y)), t);
101
- }, h = this.$W, m = this.$M, M = this.$D, I = "set" + (this.$u ? "UTC" : "");
102
- switch (i) {
103
- case x:
104
- return a ? o(1, 0) : o(31, 11);
105
- case p:
106
- return a ? o(1, m) : o(0, m + 1);
107
- case H:
108
- var z = this.$locale().weekStart || 0, N = (h < z ? h + 7 : h) - z;
109
- return o(a ? M - N : M + (6 - N), m);
110
- case v:
111
- case C:
112
- return f(I + "Hours", 0);
113
- case $:
114
- return f(I + "Minutes", 1);
115
- case _:
116
- return f(I + "Seconds", 2);
117
- case L:
118
- return f(I + "Milliseconds", 3);
119
- default:
120
- return this.clone();
121
- }
122
- }, n.endOf = function(e) {
123
- return this.startOf(e, !1);
124
- }, n.$set = function(e, r) {
125
- var t, a = u.p(e), i = "set" + (this.$u ? "UTC" : ""), o = (t = {}, t[v] = i + "Date", t[C] = i + "Date", t[p] = i + "Month", t[x] = i + "FullYear", t[$] = i + "Hours", t[_] = i + "Minutes", t[L] = i + "Seconds", t[E] = i + "Milliseconds", t)[a], f = a === v ? this.$D + (r - this.$W) : r;
126
- if (a === p || a === x) {
127
- var h = this.clone().set(C, 1);
128
- h.$d[o](f), h.init(), this.$d = h.set(C, Math.min(this.$D, h.daysInMonth())).$d;
129
- } else o && this.$d[o](f);
130
- return this.init(), this;
131
- }, n.set = function(e, r) {
132
- return this.clone().$set(e, r);
133
- }, n.get = function(e) {
134
- return this[u.p(e)]();
135
- }, n.add = function(e, r) {
136
- var t, a = this;
137
- e = Number(e);
138
- var i = u.p(r), o = function(m) {
139
- var M = d(a);
140
- return u.w(M.date(M.date() + Math.round(m * e)), a);
141
- };
142
- if (i === p) return this.set(p, this.$M + e);
143
- if (i === x) return this.set(x, this.$y + e);
144
- if (i === v) return o(1);
145
- if (i === H) return o(7);
146
- var f = (t = {}, t[_] = b, t[$] = g, t[L] = D, t)[i] || 1, h = this.$d.getTime() + e * f;
147
- return u.w(h, this);
148
- }, n.subtract = function(e, r) {
149
- return this.add(-1 * e, r);
150
- }, n.format = function(e) {
151
- var r = this, t = this.$locale();
152
- if (!this.isValid()) return t.invalidDate || P;
153
- var a = e || "YYYY-MM-DDTHH:mm:ssZ", i = u.z(this), o = this.$H, f = this.$m, h = this.$M, m = t.weekdays, M = t.months, I = t.meridiem, z = function(y, Y, F, K) {
154
- return y && (y[Y] || y(r, a)) || F[Y].slice(0, K);
155
- }, N = function(y) {
156
- return u.s(o % 12 || 12, y, "0");
157
- }, A = I || function(y, Y, F) {
158
- var K = y < 12 ? "AM" : "PM";
159
- return F ? K.toLowerCase() : K;
160
- };
161
- return a.replace(Q, function(y, Y) {
162
- return Y || function(F) {
163
- switch (F) {
164
- case "YY":
165
- return String(r.$y).slice(-2);
166
- case "YYYY":
167
- return u.s(r.$y, 4, "0");
168
- case "M":
169
- return h + 1;
170
- case "MM":
171
- return u.s(h + 1, 2, "0");
172
- case "MMM":
173
- return z(t.monthsShort, h, M, 3);
174
- case "MMMM":
175
- return z(M, h);
176
- case "D":
177
- return r.$D;
178
- case "DD":
179
- return u.s(r.$D, 2, "0");
180
- case "d":
181
- return String(r.$W);
182
- case "dd":
183
- return z(t.weekdaysMin, r.$W, m, 2);
184
- case "ddd":
185
- return z(t.weekdaysShort, r.$W, m, 3);
186
- case "dddd":
187
- return m[r.$W];
188
- case "H":
189
- return String(o);
190
- case "HH":
191
- return u.s(o, 2, "0");
192
- case "h":
193
- return N(1);
194
- case "hh":
195
- return N(2);
196
- case "a":
197
- return A(o, f, !0);
198
- case "A":
199
- return A(o, f, !1);
200
- case "m":
201
- return String(f);
202
- case "mm":
203
- return u.s(f, 2, "0");
204
- case "s":
205
- return String(r.$s);
206
- case "ss":
207
- return u.s(r.$s, 2, "0");
208
- case "SSS":
209
- return u.s(r.$ms, 3, "0");
210
- case "Z":
211
- return i;
212
- }
213
- return null;
214
- }(y) || i.replace(":", "");
215
- });
216
- }, n.utcOffset = function() {
217
- return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
218
- }, n.diff = function(e, r, t) {
219
- var a, i = this, o = u.p(r), f = d(e), h = (f.utcOffset() - this.utcOffset()) * b, m = this - f, M = function() {
220
- return u.m(i, f);
221
- };
222
- switch (o) {
223
- case x:
224
- a = M() / 12;
225
- break;
226
- case p:
227
- a = M();
228
- break;
229
- case T:
230
- a = M() / 3;
231
- break;
232
- case H:
233
- a = (m - h) / 6048e5;
234
- break;
235
- case v:
236
- a = (m - h) / 864e5;
237
- break;
238
- case $:
239
- a = m / g;
240
- break;
241
- case _:
242
- a = m / b;
243
- break;
244
- case L:
245
- a = m / D;
246
- break;
247
- default:
248
- a = m;
249
- }
250
- return t ? a : u.a(a);
251
- }, n.daysInMonth = function() {
252
- return this.endOf(p).$D;
253
- }, n.$locale = function() {
254
- return k[this.$L];
255
- }, n.locale = function(e, r) {
256
- if (!e) return this.$L;
257
- var t = this.clone(), a = U(e, r, !0);
258
- return a && (t.$L = a), t;
259
- }, n.clone = function() {
260
- return u.w(this.$d, this);
261
- }, n.toDate = function() {
262
- return new Date(this.valueOf());
263
- }, n.toJSON = function() {
264
- return this.isValid() ? this.toISOString() : null;
265
- }, n.toISOString = function() {
266
- return this.$d.toISOString();
267
- }, n.toString = function() {
268
- return this.$d.toUTCString();
269
- }, s;
270
- }(), V = q.prototype;
271
- return d.prototype = V, [["$ms", E], ["$s", L], ["$m", _], ["$H", $], ["$W", v], ["$M", p], ["$y", x], ["$D", C]].forEach(function(s) {
272
- V[s[1]] = function(n) {
273
- return this.$g(n, s[0], s[1]);
274
- };
275
- }), d.extend = function(s, n) {
276
- return s.$i || (s(n, q, d), s.$i = !0), d;
277
- }, d.locale = U, d.isDayjs = W, d.unix = function(s) {
278
- return d(1e3 * s);
279
- }, d.en = k[S], d.Ls = k, d.p = {}, d;
280
- });
281
- }(Z)), Z.exports;
282
- }
283
- var ae = se();
284
- const ie = /* @__PURE__ */ ne(ae);
285
- function ue(l) {
286
- const O = new Blob([l], {
287
- type: "application/vnd.ms-excel"
288
- // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
289
- });
290
- return window.URL.createObjectURL(O);
291
- }
292
- function oe() {
293
- return document.createElement("a");
294
- }
295
- function ce(l, O) {
296
- const D = ie().format("yyyy-MM-dd hh:mm:ss");
297
- function b() {
298
- const g = oe(), E = ue(l);
299
- g.href = E, O ? g.download = O || `${O}-${D}.xlsx` : g.download = `${D}.xlsx`, document.body.appendChild(g), g.click(), document.body.removeChild(g), window.URL.revokeObjectURL(E);
300
- }
301
- b();
302
- }
303
- function fe(l, O) {
304
- throw new Error(`[naive/${l}]: ${O}`);
305
- }
306
- const le = "n-message-api";
307
- function de() {
308
- const l = X(le, null);
309
- return l === null && fe("use-message", "No outer <n-message-provider /> founded. See prerequisite in https://www.naiveui.com/en-US/os-theme/components/message for more details. If you want to use `useMessage` outside setup, please check https://www.naiveui.com/zh-CN/os-theme/components/message#Q-&-A."), l;
310
- }
311
- function $e(l, O = {}) {
312
- const {
313
- exportRequestFn: D,
314
- filterOption: b = J(),
315
- callback: g,
316
- immediate: E = !0,
317
- code: L = 200
318
- } = O, _ = J(!1), $ = J({
319
- page: 1,
320
- pageSize: 10,
321
- itemCount: 0,
322
- showSizePicker: !0,
323
- pageSizes: [10, 20, 30, 40],
324
- showQuickJumper: !0,
325
- prefix: (c) => `共 ${c.itemCount} 条`
326
- }), v = J([]), H = ee(() => b.value), p = async (c = $.value.page, w) => {
327
- _.value = !0;
328
- try {
329
- const { status: j, data: S } = await l({
330
- pageNum: c,
331
- pageSize: $.value.pageSize,
332
- ...H.value,
333
- ...w
334
- }), { list: k, pageNum: R, total: W, pageSize: U } = g && g(S) || S;
335
- if (j === L && Array.isArray(k))
336
- v.value = k, $.value = {
337
- ...$.value,
338
- page: R,
339
- itemCount: W,
340
- pageSize: U
341
- };
342
- else
343
- throw v.value = [], $.value = {
344
- ...$.value,
345
- pageSize: 10,
346
- itemCount: 0,
347
- page: 1
348
- }, new Error("list的数据类型错误");
349
- } catch (j) {
350
- throw console.error("Error in loadData:", j), j;
351
- } finally {
352
- _.value = !1;
353
- }
354
- }, T = de(), x = async () => {
355
- if (!D || typeof D != "function")
356
- throw new Error("当前没有提供exportRequest函数");
357
- try {
358
- const { data: c, fileName: w } = await D(b.value);
359
- ce(c, w), T == null || T.success("成功导出");
360
- } catch (c) {
361
- throw console.error("Error in handleExcelData:", c), c;
362
- }
363
- }, C = (c, w) => {
364
- w !== void 0 && ($.value.pageSize = w), p(c);
365
- }, P = (c) => {
366
- C(c);
367
- }, B = (c) => {
368
- C(1, c);
369
- }, Q = (c) => {
370
- if (c.sorter) {
371
- const w = [...v.value].sort((j, S) => c.order === "ascend" ? j[c.columnKey] > S[c.columnKey] ? 1 : -1 : c.order === "descend" ? j[c.columnKey] < S[c.columnKey] ? 1 : -1 : 0);
372
- v.value = w;
373
- }
374
- };
375
- return te(() => E && p($.value.page)), {
376
- dataSource: v,
377
- loading: _,
378
- pagination: $,
379
- handleExcelData: x,
380
- handlePageChange: P,
381
- handlePageSizeChange: B,
382
- handleSortChange: Q,
383
- loadData: p
384
- };
385
- }
386
- export {
387
- ce as useExportFile,
388
- $e as useList
389
- };
1
+ export * from './useExportRemoteFile';
2
+ export * from './useList';
3
+ export * from './useTableHeight';
4
+ export * from './useAsyncData';
@@ -0,0 +1,14 @@
1
+ import type { OptionsType } from './types';
2
+ /**
3
+ * 异步请求数据的 Hook
4
+ * @param requestFn - 请求函数
5
+ * @param options - 配置
6
+ * @param options.immediate - 是否立即执行,默认为 true
7
+ * @returns
8
+ */
9
+ export declare function useAsyncDat(requestFn: () => Promise<any>, options?: OptionsType): {
10
+ data: import("vue").Ref<any, any>;
11
+ loading: import("vue").Ref<boolean, boolean>;
12
+ error: import("vue").Ref<any, any>;
13
+ fetchData: () => Promise<void>;
14
+ };
@@ -0,0 +1,37 @@
1
+ import { ref } from 'vue';
2
+ /**
3
+ * 异步请求数据的 Hook
4
+ * @param requestFn - 请求函数
5
+ * @param options - 配置
6
+ * @param options.immediate - 是否立即执行,默认为 true
7
+ * @returns
8
+ */
9
+ export function useAsyncDat(requestFn, options = {}) {
10
+ const { immediate = true } = options;
11
+ const data = ref(null);
12
+ const loading = ref(false);
13
+ const error = ref(null);
14
+ const fetchData = async () => {
15
+ loading.value = true;
16
+ error.value = null;
17
+ try {
18
+ const response = await requestFn();
19
+ data.value = response;
20
+ }
21
+ catch (err) {
22
+ error.value = err;
23
+ }
24
+ finally {
25
+ loading.value = false;
26
+ }
27
+ };
28
+ if (immediate) {
29
+ fetchData();
30
+ }
31
+ return {
32
+ data,
33
+ loading,
34
+ error,
35
+ fetchData,
36
+ };
37
+ }
@@ -0,0 +1,3 @@
1
+ export type OptionsType = {
2
+ immediate?: boolean;
3
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -5,4 +5,4 @@
5
5
  *
6
6
  * @returns {object} 返回解析后的设备信息对象
7
7
  */
8
- export declare function useDeviceInfo(): Promise<import('ua-parser-js').IResult>;
8
+ export declare function useDeviceInfo(): Promise<import("ua-parser-js").IResult>;
@@ -0,0 +1,40 @@
1
+ import { UAParser } from 'ua-parser-js';
2
+ /**
3
+ * 单例模式下的 UAParser 实例管理
4
+ */
5
+ const parserInstance = (function () {
6
+ let instance = null;
7
+ const initializing = (async () => {
8
+ try {
9
+ instance = new UAParser();
10
+ return instance;
11
+ }
12
+ catch (error) {
13
+ console.error('Failed to initialize UAParser:', error);
14
+ throw error;
15
+ }
16
+ })();
17
+ return {
18
+ /**
19
+ * 获取 UAParser 实例
20
+ * @returns 返回 {Promise<UAParser>} 解析用户代理字符串的实例
21
+ */
22
+ getInstance: async () => {
23
+ if (!instance) {
24
+ instance = await initializing;
25
+ }
26
+ return instance;
27
+ },
28
+ };
29
+ })();
30
+ /**
31
+ * 使用设备信息钩子
32
+ * 该钩子用于获取客户端设备的信息,如浏览器类型、操作系统等
33
+ * 它基于UAParser实例来解析用户代理字符串
34
+ *
35
+ * @returns {object} 返回解析后的设备信息对象
36
+ */
37
+ export async function useDeviceInfo() {
38
+ const instance = await parserInstance.getInstance();
39
+ return instance.getResult();
40
+ }
@@ -0,0 +1,56 @@
1
+ import dayjs from 'dayjs';
2
+ /**
3
+ * 将给定的数据转换为 Blob 对象,并生成一个 URL 对象,用于下载或显示该 Blob 对象
4
+ * 此函数主要用于准备数据以便在浏览器中下载或展示
5
+ *
6
+ * @param data {BlobPart} - 需要转换为 Blob 的数据部分,可以是数组、Blob、字符串等
7
+ * @returns {string} 一个 URL 对象,表示新创建的 Blob 对象的位置
8
+ */
9
+ function transformBlob(data) {
10
+ // 创建一个新的 Blob 对象,包含传入的数据部分,并指定 MIME 类型
11
+ // 此处的 MIME 类型为 'application/vnd.ms-excel',用于处理 Excel 文件
12
+ // 另一个 MIME 类型 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 用于处理 Office Open XML 格式的 Excel 文件
13
+ const blob = new Blob([data], {
14
+ type: 'application/vnd.ms-excel',
15
+ // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
16
+ });
17
+ // 使用 window.URL.createObjectURL 方法创建一个新的 URL 对象,指向 Blob 对象
18
+ // 这个 URL 可以在浏览器中直接访问,用于下载或展示 Blob 中的数据
19
+ const href = window.URL.createObjectURL(blob);
20
+ // 返回创建的 URL 对象
21
+ return href;
22
+ }
23
+ /**
24
+ * 创建一个新的 HTML 元素,通常是 <a> 标签,用于下载文件
25
+ *
26
+ * @returns {HTMLAnchorElement} 一个新创建的 <a> 标签元素
27
+ */
28
+ function createElement() {
29
+ const downloadElement = document.createElement('a');
30
+ return downloadElement;
31
+ }
32
+ /**
33
+ * 导出文件
34
+ *
35
+ * @param data - 要导出的数据
36
+ * @param fileName - 导出的文件名(可选)
37
+ */
38
+ export function useExportFile(data, fileName) {
39
+ const time = dayjs().format('yyyy-MM-dd hh:mm:ss');
40
+ function download() {
41
+ const downloadDOM = createElement();
42
+ const href = transformBlob(data);
43
+ downloadDOM.href = href;
44
+ if (fileName) {
45
+ downloadDOM.download = fileName || `${fileName}-${time}.xlsx`;
46
+ }
47
+ else {
48
+ downloadDOM.download = `${time}.xlsx`;
49
+ }
50
+ document.body.appendChild(downloadDOM);
51
+ downloadDOM.click();
52
+ document.body.removeChild(downloadDOM);
53
+ window.URL.revokeObjectURL(href);
54
+ }
55
+ download();
56
+ }
@@ -1,9 +1,9 @@
1
- import { OptionsType } from './types';
2
- import { DataTableSortState } from 'naive-ui';
1
+ import type { OptionsType } from './types';
2
+ import { type DataTableSortState } from 'naive-ui';
3
3
  export declare function useList<T extends (...args: any) => Promise<any>>(listRequestFn: T, options?: OptionsType): {
4
- dataSource: import('vue').Ref<any[], any[]>;
5
- loading: import('vue').Ref<boolean, boolean>;
6
- pagination: import('vue').Ref<{
4
+ dataSource: import("vue").Ref<any[], any[]>;
5
+ loading: import("vue").Ref<boolean, boolean>;
6
+ pagination: import("vue").Ref<{
7
7
  page: number;
8
8
  pageSize: number;
9
9
  itemCount: number;
@@ -34,4 +34,3 @@ export declare function useList<T extends (...args: any) => Promise<any>>(listRe
34
34
  handleSortChange: (options: DataTableSortState) => void;
35
35
  loadData: (page?: number, filterParams?: any) => Promise<void>;
36
36
  };
37
- export default useList;
@@ -0,0 +1,127 @@
1
+ import { useMessage } from 'naive-ui';
2
+ import { computed, onMounted, ref } from 'vue';
3
+ import { useExportFile } from '../useExportRemoteFile';
4
+ // import { getPagination } from '@/utils'
5
+ export function useList(listRequestFn, options = {}) {
6
+ const { exportRequestFn, filterOption = ref(), callback, immediate = true, code = 200, } = options;
7
+ // 加载态
8
+ const loading = ref(false);
9
+ const pagination = ref({
10
+ page: 1,
11
+ pageSize: 10,
12
+ itemCount: 0,
13
+ showSizePicker: true,
14
+ pageSizes: [10, 20, 30, 40],
15
+ showQuickJumper: true,
16
+ prefix: (info) => `共 ${info.itemCount} 条`,
17
+ });
18
+ // 数据
19
+ const dataSource = ref([]);
20
+ const searchParams = computed(() => {
21
+ return filterOption.value;
22
+ });
23
+ /**
24
+ * 加载数据
25
+ * @param page - 当前页
26
+ * @param pageSize - 页数
27
+ */
28
+ const loadData = async (page = pagination.value.page, filterParams) => {
29
+ loading.value = true;
30
+ try {
31
+ const { status, data } = await listRequestFn({
32
+ pageNum: page,
33
+ pageSize: pagination.value.pageSize,
34
+ ...searchParams.value,
35
+ ...filterParams,
36
+ });
37
+ const { list, pageNum, total, pageSize } = (callback && callback(data)) || data;
38
+ if (status === code && Array.isArray(list)) {
39
+ dataSource.value = list;
40
+ pagination.value = {
41
+ ...pagination.value,
42
+ page: pageNum,
43
+ itemCount: total,
44
+ pageSize,
45
+ };
46
+ }
47
+ else {
48
+ dataSource.value = [];
49
+ pagination.value = {
50
+ ...pagination.value,
51
+ pageSize: 10,
52
+ itemCount: 0,
53
+ page: 1,
54
+ };
55
+ throw new Error('list的数据类型错误');
56
+ }
57
+ }
58
+ catch (error) {
59
+ console.error('Error in loadData:', error);
60
+ throw error;
61
+ }
62
+ finally {
63
+ loading.value = false;
64
+ }
65
+ };
66
+ const message = useMessage();
67
+ /**
68
+ * 导出文件
69
+ */
70
+ const handleExcelData = async () => {
71
+ if (!exportRequestFn || typeof exportRequestFn !== 'function') {
72
+ throw new Error('当前没有提供exportRequest函数');
73
+ }
74
+ try {
75
+ const { data, fileName } = await exportRequestFn(filterOption.value);
76
+ // eslint-disable-next-line react-hooks/rules-of-hooks
77
+ useExportFile(data, fileName);
78
+ message?.success('成功导出');
79
+ }
80
+ catch (error) {
81
+ console.error('Error in handleExcelData:', error);
82
+ throw error;
83
+ }
84
+ };
85
+ /**
86
+ * 更新分页并加载数据
87
+ * @param page - 当前页
88
+ * @param pageSize - 每页条数
89
+ */
90
+ const updatePaginationAndLoadData = (page, pageSize) => {
91
+ if (pageSize !== undefined) {
92
+ pagination.value.pageSize = pageSize;
93
+ }
94
+ loadData(page);
95
+ };
96
+ const handlePageChange = (page) => {
97
+ updatePaginationAndLoadData(page);
98
+ };
99
+ const handlePageSizeChange = (pageSize) => {
100
+ updatePaginationAndLoadData(1, pageSize);
101
+ };
102
+ const handleSortChange = (options) => {
103
+ if (options.sorter) {
104
+ const sortData = [...dataSource.value].sort((a, b) => {
105
+ if (options.order === 'ascend') {
106
+ return a[options.columnKey] > b[options.columnKey] ? 1 : -1;
107
+ }
108
+ if (options.order === 'descend') {
109
+ return a[options.columnKey] < b[options.columnKey] ? 1 : -1;
110
+ }
111
+ return 0;
112
+ });
113
+ dataSource.value = sortData;
114
+ }
115
+ };
116
+ onMounted(() => immediate && loadData(pagination.value.page));
117
+ return {
118
+ dataSource,
119
+ loading,
120
+ pagination,
121
+ handleExcelData,
122
+ handlePageChange,
123
+ handlePageSizeChange,
124
+ handleSortChange,
125
+ loadData,
126
+ };
127
+ }
@@ -1,4 +1,4 @@
1
- import { Ref } from 'vue';
1
+ import type { Ref } from 'vue';
2
2
  export interface OptionsType<T = any> {
3
3
  requestError?: () => void;
4
4
  requestSuccess?: () => void;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ interface Options {
2
+ height?: number;
3
+ minHeight?: number;
4
+ }
5
+ /**
6
+ * useTableHeight
7
+ *
8
+ * @description 计算表格高度
9
+ * @example const { height } = useTableHeight(tableRef, { height: 100, minHeight: 600 })
10
+ *
11
+ * @param tableRef - 表格元素引用
12
+ * @param options - 表格高度配置
13
+ * @param options.height - 表格之外的高度值
14
+ * @param options.minHeight - 表格的最小高度
15
+ * @returns { height } - 表格高度
16
+ */
17
+ export declare function useTableHeight(tableRef: any, options?: Options): {
18
+ height: import("vue").ComputedRef<number>;
19
+ };
20
+ export {};
@@ -0,0 +1,39 @@
1
+ import { useElementSize, useWindowSize } from '@vueuse/core';
2
+ import { computed } from 'vue';
3
+ /**
4
+ * useTableHeight
5
+ *
6
+ * @description 计算表格高度
7
+ * @example const { height } = useTableHeight(tableRef, { height: 100, minHeight: 600 })
8
+ *
9
+ * @param tableRef - 表格元素引用
10
+ * @param options - 表格高度配置
11
+ * @param options.height - 表格之外的高度值
12
+ * @param options.minHeight - 表格的最小高度
13
+ * @returns { height } - 表格高度
14
+ */
15
+ export function useTableHeight(tableRef, options) {
16
+ // 验证参数
17
+ if (!tableRef)
18
+ throw new Error('tableRef are required');
19
+ // 获取搜索栏元素引用
20
+ const searchRef = computed(() => tableRef.value?.searchRef);
21
+ // 获取窗口高度和搜索栏高度
22
+ const { height: winHeight } = useWindowSize();
23
+ const { height: searchHeight } = useElementSize(searchRef.value);
24
+ // 获取表格高度和最小高度
25
+ const { height = 0, minHeight = 600 } = options || {};
26
+ // 计算表格高度
27
+ const tableHeight = computed(() => {
28
+ const h = winHeight.value -
29
+ searchHeight.value -
30
+ height;
31
+ if (h > minHeight) {
32
+ return h;
33
+ }
34
+ return minHeight;
35
+ });
36
+ return {
37
+ height: tableHeight
38
+ };
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banmao/hooks",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -17,21 +17,17 @@
17
17
  ],
18
18
  "devDependencies": {
19
19
  "@vue/tsconfig": "^0.7.0",
20
- "echarts": "^5.6.0",
21
20
  "glob": "^11.0.0",
22
21
  "naive-ui": "^2.41.0",
23
22
  "typescript": "~5.6.2",
24
23
  "vite": "^6.0.5",
25
24
  "vite-plugin-compression": "^0.5.1",
26
25
  "vue": "^3.5.13",
27
- "vue-echarts": "^7.0.3",
28
26
  "vue-tsc": "^2.2.0"
29
27
  },
30
28
  "peerDependencies": {
31
- "echarts": "^5.6.0",
32
29
  "naive-ui": "^2.41.0",
33
- "vue": "^3.5.13",
34
- "vue-echarts": "^7.0.3"
30
+ "vue": "^3.5.13"
35
31
  },
36
32
  "dependencies": {
37
33
  "dayjs": "^1.11.13",
package/dist/index.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("vue");function ee(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Z={exports:{}},te=Z.exports,G;function ne(){return G||(G=1,function(l,b){(function(D,O){l.exports=O()})(te,function(){var D=1e3,O=6e4,g=36e5,E="millisecond",L="second",_="minute",$="hour",v="day",H="week",p="month",U="quarter",x="year",j="date",q="Invalid Date",B=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,Q=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,c={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(s){var n=["th","st","nd","rd"],e=s%100;return"["+s+(n[(e-20)%10]||n[e]||n[0])+"]"}},w=function(s,n,e){var r=String(s);return!r||r.length>=n?s:""+Array(n+1-r.length).join(e)+s},C={s:w,z:function(s){var n=-s.utcOffset(),e=Math.abs(n),r=Math.floor(e/60),t=e%60;return(n<=0?"+":"-")+w(r,2,"0")+":"+w(t,2,"0")},m:function s(n,e){if(n.date()<e.date())return-s(e,n);var r=12*(e.year()-n.year())+(e.month()-n.month()),t=n.clone().add(r,p),a=e-t<0,i=n.clone().add(r+(a?-1:1),p);return+(-(r+(e-t)/(a?t-i:i-t))||0)},a:function(s){return s<0?Math.ceil(s)||0:Math.floor(s)},p:function(s){return{M:p,y:x,w:H,d:v,D:j,h:$,m:_,s:L,ms:E,Q:U}[s]||String(s||"").toLowerCase().replace(/s$/,"")},u:function(s){return s===void 0}},S="en",k={};k[S]=c;var R="$isDayjsObject",F=function(s){return s instanceof K||!(!s||!s[R])},I=function s(n,e,r){var t;if(!n)return S;if(typeof n=="string"){var a=n.toLowerCase();k[a]&&(t=a),e&&(k[a]=e,t=a);var i=n.split("-");if(!t&&i.length>1)return s(i[0])}else{var o=n.name;k[o]=n,t=o}return!r&&t&&(S=t),t||!r&&S},d=function(s,n){if(F(s))return s.clone();var e=typeof n=="object"?n:{};return e.date=s,e.args=arguments,new K(e)},u=C;u.l=I,u.i=F,u.w=function(s,n){return d(s,{locale:n.$L,utc:n.$u,x:n.$x,$offset:n.$offset})};var K=function(){function s(e){this.$L=I(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[R]=!0}var n=s.prototype;return n.parse=function(e){this.$d=function(r){var t=r.date,a=r.utc;if(t===null)return new Date(NaN);if(u.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t=="string"&&!/Z$/i.test(t)){var i=t.match(B);if(i){var o=i[2]-1||0,f=(i[7]||"0").substring(0,3);return a?new Date(Date.UTC(i[1],o,i[3]||1,i[4]||0,i[5]||0,i[6]||0,f)):new Date(i[1],o,i[3]||1,i[4]||0,i[5]||0,i[6]||0,f)}}return new Date(t)}(e),this.init()},n.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},n.$utils=function(){return u},n.isValid=function(){return this.$d.toString()!==q},n.isSame=function(e,r){var t=d(e);return this.startOf(r)<=t&&t<=this.endOf(r)},n.isAfter=function(e,r){return d(e)<this.startOf(r)},n.isBefore=function(e,r){return this.endOf(r)<d(e)},n.$g=function(e,r,t){return u.u(e)?this[r]:this.set(t,e)},n.unix=function(){return Math.floor(this.valueOf()/1e3)},n.valueOf=function(){return this.$d.getTime()},n.startOf=function(e,r){var t=this,a=!!u.u(r)||r,i=u.p(e),o=function(z,y){var T=u.w(t.$u?Date.UTC(t.$y,y,z):new Date(t.$y,y,z),t);return a?T:T.endOf(v)},f=function(z,y){return u.w(t.toDate()[z].apply(t.toDate("s"),(a?[0,0,0,0]:[23,59,59,999]).slice(y)),t)},h=this.$W,m=this.$M,M=this.$D,W="set"+(this.$u?"UTC":"");switch(i){case x:return a?o(1,0):o(31,11);case p:return a?o(1,m):o(0,m+1);case H:var Y=this.$locale().weekStart||0,N=(h<Y?h+7:h)-Y;return o(a?M-N:M+(6-N),m);case v:case j:return f(W+"Hours",0);case $:return f(W+"Minutes",1);case _:return f(W+"Seconds",2);case L:return f(W+"Milliseconds",3);default:return this.clone()}},n.endOf=function(e){return this.startOf(e,!1)},n.$set=function(e,r){var t,a=u.p(e),i="set"+(this.$u?"UTC":""),o=(t={},t[v]=i+"Date",t[j]=i+"Date",t[p]=i+"Month",t[x]=i+"FullYear",t[$]=i+"Hours",t[_]=i+"Minutes",t[L]=i+"Seconds",t[E]=i+"Milliseconds",t)[a],f=a===v?this.$D+(r-this.$W):r;if(a===p||a===x){var h=this.clone().set(j,1);h.$d[o](f),h.init(),this.$d=h.set(j,Math.min(this.$D,h.daysInMonth())).$d}else o&&this.$d[o](f);return this.init(),this},n.set=function(e,r){return this.clone().$set(e,r)},n.get=function(e){return this[u.p(e)]()},n.add=function(e,r){var t,a=this;e=Number(e);var i=u.p(r),o=function(m){var M=d(a);return u.w(M.date(M.date()+Math.round(m*e)),a)};if(i===p)return this.set(p,this.$M+e);if(i===x)return this.set(x,this.$y+e);if(i===v)return o(1);if(i===H)return o(7);var f=(t={},t[_]=O,t[$]=g,t[L]=D,t)[i]||1,h=this.$d.getTime()+e*f;return u.w(h,this)},n.subtract=function(e,r){return this.add(-1*e,r)},n.format=function(e){var r=this,t=this.$locale();if(!this.isValid())return t.invalidDate||q;var a=e||"YYYY-MM-DDTHH:mm:ssZ",i=u.z(this),o=this.$H,f=this.$m,h=this.$M,m=t.weekdays,M=t.months,W=t.meridiem,Y=function(y,T,P,J){return y&&(y[T]||y(r,a))||P[T].slice(0,J)},N=function(y){return u.s(o%12||12,y,"0")},z=W||function(y,T,P){var J=y<12?"AM":"PM";return P?J.toLowerCase():J};return a.replace(Q,function(y,T){return T||function(P){switch(P){case"YY":return String(r.$y).slice(-2);case"YYYY":return u.s(r.$y,4,"0");case"M":return h+1;case"MM":return u.s(h+1,2,"0");case"MMM":return Y(t.monthsShort,h,M,3);case"MMMM":return Y(M,h);case"D":return r.$D;case"DD":return u.s(r.$D,2,"0");case"d":return String(r.$W);case"dd":return Y(t.weekdaysMin,r.$W,m,2);case"ddd":return Y(t.weekdaysShort,r.$W,m,3);case"dddd":return m[r.$W];case"H":return String(o);case"HH":return u.s(o,2,"0");case"h":return N(1);case"hh":return N(2);case"a":return z(o,f,!0);case"A":return z(o,f,!1);case"m":return String(f);case"mm":return u.s(f,2,"0");case"s":return String(r.$s);case"ss":return u.s(r.$s,2,"0");case"SSS":return u.s(r.$ms,3,"0");case"Z":return i}return null}(y)||i.replace(":","")})},n.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},n.diff=function(e,r,t){var a,i=this,o=u.p(r),f=d(e),h=(f.utcOffset()-this.utcOffset())*O,m=this-f,M=function(){return u.m(i,f)};switch(o){case x:a=M()/12;break;case p:a=M();break;case U:a=M()/3;break;case H:a=(m-h)/6048e5;break;case v:a=(m-h)/864e5;break;case $:a=m/g;break;case _:a=m/O;break;case L:a=m/D;break;default:a=m}return t?a:u.a(a)},n.daysInMonth=function(){return this.endOf(p).$D},n.$locale=function(){return k[this.$L]},n.locale=function(e,r){if(!e)return this.$L;var t=this.clone(),a=I(e,r,!0);return a&&(t.$L=a),t},n.clone=function(){return u.w(this.$d,this)},n.toDate=function(){return new Date(this.valueOf())},n.toJSON=function(){return this.isValid()?this.toISOString():null},n.toISOString=function(){return this.$d.toISOString()},n.toString=function(){return this.$d.toUTCString()},s}(),V=K.prototype;return d.prototype=V,[["$ms",E],["$s",L],["$m",_],["$H",$],["$W",v],["$M",p],["$y",x],["$D",j]].forEach(function(s){V[s[1]]=function(n){return this.$g(n,s[0],s[1])}}),d.extend=function(s,n){return s.$i||(s(n,K,d),s.$i=!0),d},d.locale=I,d.isDayjs=F,d.unix=function(s){return d(1e3*s)},d.en=k[S],d.Ls=k,d.p={},d})}(Z)),Z.exports}var re=ne();const se=ee(re);function ae(l){const b=new Blob([l],{type:"application/vnd.ms-excel"});return window.URL.createObjectURL(b)}function ie(){return document.createElement("a")}function X(l,b){const D=se().format("yyyy-MM-dd hh:mm:ss");function O(){const g=ie(),E=ae(l);g.href=E,b?g.download=b||`${b}-${D}.xlsx`:g.download=`${D}.xlsx`,document.body.appendChild(g),g.click(),document.body.removeChild(g),window.URL.revokeObjectURL(E)}O()}function ue(l,b){throw new Error(`[naive/${l}]: ${b}`)}const oe="n-message-api";function ce(){const l=A.inject(oe,null);return l===null&&ue("use-message","No outer <n-message-provider /> founded. See prerequisite in https://www.naiveui.com/en-US/os-theme/components/message for more details. If you want to use `useMessage` outside setup, please check https://www.naiveui.com/zh-CN/os-theme/components/message#Q-&-A."),l}function fe(l,b={}){const{exportRequestFn:D,filterOption:O=A.ref(),callback:g,immediate:E=!0,code:L=200}=b,_=A.ref(!1),$=A.ref({page:1,pageSize:10,itemCount:0,showSizePicker:!0,pageSizes:[10,20,30,40],showQuickJumper:!0,prefix:c=>`共 ${c.itemCount} 条`}),v=A.ref([]),H=A.computed(()=>O.value),p=async(c=$.value.page,w)=>{_.value=!0;try{const{status:C,data:S}=await l({pageNum:c,pageSize:$.value.pageSize,...H.value,...w}),{list:k,pageNum:R,total:F,pageSize:I}=g&&g(S)||S;if(C===L&&Array.isArray(k))v.value=k,$.value={...$.value,page:R,itemCount:F,pageSize:I};else throw v.value=[],$.value={...$.value,pageSize:10,itemCount:0,page:1},new Error("list的数据类型错误")}catch(C){throw console.error("Error in loadData:",C),C}finally{_.value=!1}},U=ce(),x=async()=>{if(!D||typeof D!="function")throw new Error("当前没有提供exportRequest函数");try{const{data:c,fileName:w}=await D(O.value);X(c,w),U==null||U.success("成功导出")}catch(c){throw console.error("Error in handleExcelData:",c),c}},j=(c,w)=>{w!==void 0&&($.value.pageSize=w),p(c)},q=c=>{j(c)},B=c=>{j(1,c)},Q=c=>{if(c.sorter){const w=[...v.value].sort((C,S)=>c.order==="ascend"?C[c.columnKey]>S[c.columnKey]?1:-1:c.order==="descend"?C[c.columnKey]<S[c.columnKey]?1:-1:0);v.value=w}};return A.onMounted(()=>E&&p($.value.page)),{dataSource:v,loading:_,pagination:$,handleExcelData:x,handlePageChange:q,handlePageSizeChange:B,handleSortChange:Q,loadData:p}}exports.useExportFile=X;exports.useList=fe;