@jnrs/vue-core 1.0.1

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.
@@ -0,0 +1 @@
1
+ export * as router from './utils/router';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * as router from './utils/router';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 默认配置项
3
+ * @property history - 路由历史模式
4
+ * @property routes - 路由记录数组
5
+ */
6
+ declare const DEFAULT_OPTIONS: {
7
+ history: import("vue-router").RouterHistory;
8
+ routes: never[];
9
+ };
10
+ /**
11
+ * 默认布局名称
12
+ * @description 用于标识应用的主布局组件
13
+ */
14
+ declare const LAYOUT_NAME = "Layout";
15
+ /**
16
+ * 模块基础路径
17
+ * @description 用于动态导入视图组件的基础路径
18
+ */
19
+ declare const MODULES_BASE = "";
20
+ /**
21
+ * 异步获取菜单项的默认实现
22
+ * @returns 空菜单项数组的 Promise
23
+ */
24
+ declare const asyncGetMenus: () => Promise<never[]>;
25
+ export { DEFAULT_OPTIONS, LAYOUT_NAME, MODULES_BASE, asyncGetMenus };
@@ -0,0 +1,26 @@
1
+ import { createWebHistory } from 'vue-router';
2
+ /**
3
+ * 默认配置项
4
+ * @property history - 路由历史模式
5
+ * @property routes - 路由记录数组
6
+ */
7
+ const DEFAULT_OPTIONS = {
8
+ history: createWebHistory(),
9
+ routes: []
10
+ };
11
+ /**
12
+ * 默认布局名称
13
+ * @description 用于标识应用的主布局组件
14
+ */
15
+ const LAYOUT_NAME = 'Layout';
16
+ /**
17
+ * 模块基础路径
18
+ * @description 用于动态导入视图组件的基础路径
19
+ */
20
+ const MODULES_BASE = '';
21
+ /**
22
+ * 异步获取菜单项的默认实现
23
+ * @returns 空菜单项数组的 Promise
24
+ */
25
+ const asyncGetMenus = () => Promise.resolve([]);
26
+ export { DEFAULT_OPTIONS, LAYOUT_NAME, MODULES_BASE, asyncGetMenus };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @Author : TanRui
3
+ * @WeChat : Tan578853789
4
+ * @File : index.ts
5
+ * @Date : 2025/10/07
6
+ * @Desc. : 路由入口
7
+ */
8
+ import { useRoute, type RouteLocationRaw, type NavigationFailure } from 'vue-router';
9
+ import type { MenuItem, CreateVueRouterOptions } from './types';
10
+ /**
11
+ * 创建 Vue Router 实例
12
+ * @param options - 实例的配置项
13
+ * @param layoutName - 布局组件名称,默认为 'Layout'
14
+ * @param modulesBase - 模块基础路径,默认为 ''
15
+ * @param modulesList - 模块列表对象
16
+ * @param asyncGetMenusFn - 异步获取菜单项处理函数
17
+ * @returns router 路由实例
18
+ * @returns setupDynamicRoutes 动态路由加载函数
19
+ * @returns useRoute 路由使用函数
20
+ * @returns routerPush 路由跳转函数
21
+ * @returns routerReplace 路由替换函数
22
+ * @returns getRoutes 获取路由函数
23
+ * @example const { router, setupDynamicRoutes } = createVueRouter({})
24
+ */
25
+ declare const createVueRouter: ({ options, layoutName, modulesBase, modulesList, asyncGetMenusFn }?: CreateVueRouterOptions) => {
26
+ router: import("vue-router").Router;
27
+ setupDynamicRoutes: () => Promise<void>;
28
+ useRoute: typeof useRoute;
29
+ routerPush: (to: RouteLocationRaw) => Promise<undefined | void | NavigationFailure>;
30
+ routerReplace: (to: RouteLocationRaw) => Promise<undefined | void | NavigationFailure>;
31
+ getRoutes: () => MenuItem[];
32
+ };
33
+ export { createVueRouter };
@@ -0,0 +1,162 @@
1
+ /**
2
+ * @Author : TanRui
3
+ * @WeChat : Tan578853789
4
+ * @File : index.ts
5
+ * @Date : 2025/10/07
6
+ * @Desc. : 路由入口
7
+ */
8
+ import { createRouter, useRoute } from 'vue-router';
9
+ import { DEFAULT_OPTIONS, LAYOUT_NAME, MODULES_BASE, asyncGetMenus } from './defaults';
10
+ /**
11
+ * 创建 Vue Router 实例
12
+ * @param options - 实例的配置项
13
+ * @param layoutName - 布局组件名称,默认为 'Layout'
14
+ * @param modulesBase - 模块基础路径,默认为 ''
15
+ * @param modulesList - 模块列表对象
16
+ * @param asyncGetMenusFn - 异步获取菜单项处理函数
17
+ * @returns router 路由实例
18
+ * @returns setupDynamicRoutes 动态路由加载函数
19
+ * @returns useRoute 路由使用函数
20
+ * @returns routerPush 路由跳转函数
21
+ * @returns routerReplace 路由替换函数
22
+ * @returns getRoutes 获取路由函数
23
+ * @example const { router, setupDynamicRoutes } = createVueRouter({})
24
+ */
25
+ const createVueRouter = ({ options = {}, layoutName = LAYOUT_NAME, modulesBase = MODULES_BASE, modulesList = [], asyncGetMenusFn } = {}) => {
26
+ const ops = { ...DEFAULT_OPTIONS, ...options };
27
+ // 创建路由实例
28
+ const router = createRouter(ops);
29
+ // 组件加载器
30
+ const getComponentLoader = (safePath) => {
31
+ // console.log(modulesBase + `/src/views${safePath}.vue`)
32
+ return modulesList[modulesBase + `/src/views${safePath}.vue`];
33
+ };
34
+ // 异步获取菜单项处理函数
35
+ const handleAsyncGetMenus = asyncGetMenusFn ?? asyncGetMenus;
36
+ // 将菜单项转换为路由记录
37
+ const menuToRoute = async (menus, parent) => {
38
+ for (const menu of menus) {
39
+ menu.meta.fullPathTitle = parent
40
+ ? parent.meta.fullPathTitle + ',' + menu.meta.title
41
+ : menu.meta.title;
42
+ // 当前项若没有component,则为目录,直接递归处理
43
+ if (!menu.component) {
44
+ if (menu.children && menu.children.length > 0) {
45
+ await menuToRoute(menu.children, menu);
46
+ }
47
+ continue;
48
+ }
49
+ // 安全处理组件路径
50
+ const safePath = menu.component.replace(/[^a-zA-Z0-9/._-]/g, '');
51
+ if (!safePath.startsWith('/') || safePath.includes('..')) {
52
+ console.warn('[Router] 组件加载失败', {
53
+ code: 'INVALID_COMPONENT_PATH',
54
+ message: `组件路径拼写不符合规则,应以 '/' 开头且不能包含 '..',请检查 component 字段是否配置正确`,
55
+ menu: {
56
+ path: menu.path,
57
+ name: menu.name,
58
+ component: menu.component
59
+ },
60
+ timestamp: new Date().toISOString()
61
+ });
62
+ continue;
63
+ }
64
+ // 获取组件加载器
65
+ const loader = getComponentLoader(safePath);
66
+ if (!loader) {
67
+ console.warn('[Router] 组件加载失败', {
68
+ code: 'COMPONENT_NOT_FOUND',
69
+ message: `组件加载器无效,请检查 component 字段是否配置正确`,
70
+ menu: {
71
+ path: menu.path,
72
+ name: menu.name,
73
+ component: menu.component
74
+ },
75
+ timestamp: new Date().toISOString()
76
+ });
77
+ continue;
78
+ }
79
+ // 构建路由记录
80
+ const routeRecord = {
81
+ name: menu.name,
82
+ path: menu.path,
83
+ meta: menu.meta,
84
+ redirect: menu.redirect,
85
+ component: () => loader()
86
+ };
87
+ // 根据 global 字段决定添加为全局路由还是布局子路由
88
+ if (menu.meta?.global) {
89
+ router.addRoute(routeRecord);
90
+ }
91
+ else {
92
+ router.addRoute(layoutName, routeRecord);
93
+ }
94
+ }
95
+ };
96
+ // 加载动态路由
97
+ const setupDynamicRoutes = async () => {
98
+ const userRoutes = await handleAsyncGetMenus();
99
+ menuToRoute(userRoutes);
100
+ };
101
+ // 获取用户权限
102
+ const canUserAccess = async (to) => {
103
+ const isAuthenticated = true;
104
+ return to.name === 'Login' || to.meta.noAuth || isAuthenticated;
105
+ };
106
+ // 全局前置守卫
107
+ router.beforeEach(async (to) => {
108
+ const canAccess = await canUserAccess(to);
109
+ if (!canAccess) {
110
+ return {
111
+ name: 'Login',
112
+ query: { redirect: to.name?.toString() }
113
+ };
114
+ }
115
+ });
116
+ // 路由跳转
117
+ const routerPush = async (to) => {
118
+ try {
119
+ const failure = await router.push(to);
120
+ return failure;
121
+ }
122
+ catch (e) {
123
+ console.warn('[router.push] 失败', {
124
+ code: 'ROUTER_NOT_MATCH',
125
+ message: '未匹配到有效路由',
126
+ error: to || e,
127
+ timestamp: new Date().toISOString()
128
+ });
129
+ router.push({ name: '404' });
130
+ }
131
+ };
132
+ // 路由替换
133
+ const routerReplace = async (to) => {
134
+ try {
135
+ const failure = await router.replace(to);
136
+ return failure;
137
+ }
138
+ catch (e) {
139
+ console.warn('[router.replace] 失败', {
140
+ code: 'ROUTER_NOT_MATCH',
141
+ message: '未匹配到有效路由',
142
+ error: to || e,
143
+ timestamp: new Date().toISOString()
144
+ });
145
+ router.replace({ name: '404' });
146
+ }
147
+ };
148
+ // 获取路由
149
+ const getRoutes = () => {
150
+ const temp = [];
151
+ for (const route of router.getRoutes()) {
152
+ temp.push({
153
+ name: route.name,
154
+ path: route.path,
155
+ meta: route.meta
156
+ });
157
+ }
158
+ return temp;
159
+ };
160
+ return { router, setupDynamicRoutes, useRoute, routerPush, routerReplace, getRoutes };
161
+ };
162
+ export { createVueRouter };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@jnrs/vue-core",
3
+ "version": "1.0.1",
4
+ "description": "As the name suggests.",
5
+ "author": "Talia-Tan",
6
+ "license": "ISC",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "type": "module",
11
+ "keywords": [
12
+ "jnrs",
13
+ "vue-core",
14
+ "typescript",
15
+ "helper"
16
+ ],
17
+ "main": "dist/index.js",
18
+ "module": "dist/index.js",
19
+ "types": "dist/index.d.ts",
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "exports": {
26
+ ".": {
27
+ "import": "./dist/index.js",
28
+ "types": "./dist/index.d.ts"
29
+ }
30
+ },
31
+ "dependencies": {
32
+ "vue-router": "^4.5.1"
33
+ },
34
+ "devDependencies": {
35
+ "rimraf": "^6.0.1",
36
+ "typescript": "^5.9.3"
37
+ },
38
+ "scripts": {
39
+ "dev": "tsc --watch --declaration --outDir dist",
40
+ "build": "rimraf dist && tsc",
41
+ "release": "node ./scripts/release.mjs"
42
+ }
43
+ }