vue3-django 0.1.2 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue3-django",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "DRF metadata-driven Vue 3 framework",
5
5
  "keywords": [
6
6
  "vue3",
@@ -0,0 +1,35 @@
1
+ <script setup>
2
+ import { RouterView } from 'vue-router'
3
+ defineOptions({ name: 'DjangoApp' })
4
+ </script>
5
+
6
+ <template>
7
+ <div
8
+ class="vd-app"
9
+ v-cloak
10
+ >
11
+ <RouterView />
12
+ </div>
13
+ </template>
14
+
15
+ <style>
16
+ body:has(.vd-app) {
17
+ margin: var(--vd-body-margin, 0);
18
+ }
19
+ .vd-app[v-cloak] {
20
+ display: none;
21
+ }
22
+ .vd-app {
23
+ color: var(--vd-text-color, #253447);
24
+ background: var(--vd-background, white);
25
+ font-family:
26
+ system-ui,
27
+ -apple-system,
28
+ sans-serif;
29
+ }
30
+ .vd-app .vd-model-page {
31
+ width: 100%;
32
+ box-sizing: border-box;
33
+ padding: var(--vd-page-padding, 0 4px 12px);
34
+ }
35
+ </style>
@@ -0,0 +1,26 @@
1
+ <script setup>
2
+ import { useDjango } from '../composables/context.js'
3
+ const { application } = useDjango()
4
+ </script>
5
+
6
+ <template>
7
+ <main class="vd-model-page vd-home">
8
+ <h1>Welcome</h1>
9
+ <p>欢迎使用 {{ application.title }},请从侧边栏选择功能。</p>
10
+ </main>
11
+ </template>
12
+
13
+ <style scoped>
14
+ .vd-home {
15
+ padding: var(--vd-home-padding, 24px);
16
+ }
17
+ h1 {
18
+ margin: 0 0 12px;
19
+ font-size: 24px;
20
+ font-weight: 500;
21
+ }
22
+ p {
23
+ margin: 0;
24
+ color: var(--el-text-color-secondary, #909399);
25
+ }
26
+ </style>
@@ -0,0 +1,59 @@
1
+ <script setup>
2
+ import { ref } from 'vue'
3
+ import { useRoute, useRouter } from 'vue-router'
4
+ import Form from '../components/form/Form.vue'
5
+ import { useDjango } from '../composables/context.js'
6
+ import { safeRedirect } from '../router/index.js'
7
+
8
+ const { auth, application } = useDjango()
9
+ const router = useRouter()
10
+ const route = useRoute()
11
+ const values = ref({ username: '', password: '' })
12
+ const items = [
13
+ { name: 'username', label: '帐号', required: true, autocomplete: 'username' },
14
+ {
15
+ name: 'password',
16
+ label: '密码',
17
+ required: true,
18
+ widget: 'password',
19
+ autocomplete: 'current-password',
20
+ },
21
+ ]
22
+ function submit({ formValue }) {
23
+ return auth.login(formValue.username, formValue.password)
24
+ }
25
+ async function done() {
26
+ values.value.password = ''
27
+ await router.replace(safeRedirect(route.query.redirect, application.homePath))
28
+ }
29
+ </script>
30
+
31
+ <template>
32
+ <main class="vd-login">
33
+ <Form
34
+ v-model="values"
35
+ :items="items"
36
+ :submit="submit"
37
+ submit-name="登录"
38
+ success-info="登录成功"
39
+ one-column
40
+ label-position="top"
41
+ @form-posted="done"
42
+ >
43
+ <template #header>
44
+ <h1>登录 {{ application.title }}</h1>
45
+ </template>
46
+ </Form>
47
+ </main>
48
+ </template>
49
+
50
+ <style scoped>
51
+ .vd-login {
52
+ max-width: 400px;
53
+ margin: 80px auto;
54
+ padding: 24px;
55
+ }
56
+ h1 {
57
+ font-size: 24px;
58
+ }
59
+ </style>
@@ -0,0 +1,42 @@
1
+ <script setup>
2
+ import { computed, ref } from 'vue'
3
+ import { useRouter } from 'vue-router'
4
+ import { ElAlert } from 'element-plus'
5
+ import Layout from '../components/layout/Layout.vue'
6
+ import { genMenusFromApps } from '../core/menus.js'
7
+ import { useDjango } from '../composables/context.js'
8
+
9
+ const { auth, apps, application } = useDjango()
10
+ const router = useRouter()
11
+ const layout = ref()
12
+ const error = ref('')
13
+ const menus = computed(
14
+ () => application.menus ?? genMenusFromApps(apps, undefined, auth?.state.user?.model_permissions),
15
+ )
16
+ async function logout() {
17
+ try {
18
+ await auth?.logout()
19
+ layout.value?.resetTabs()
20
+ await router.replace(application.loginPath)
21
+ } catch (cause) {
22
+ error.value = cause.message
23
+ }
24
+ }
25
+ </script>
26
+
27
+ <template>
28
+ <ElAlert
29
+ v-if="error"
30
+ :title="error"
31
+ type="error"
32
+ />
33
+ <Layout
34
+ ref="layout"
35
+ v-bind="application.layoutProps"
36
+ :title="application.title"
37
+ :menus="menus"
38
+ :user="auth?.state.user"
39
+ @logout="logout"
40
+ @error="error = $event.message"
41
+ />
42
+ </template>
@@ -0,0 +1,102 @@
1
+ import { createApp, h, reactive } from 'vue'
2
+ import { ElConfigProvider } from 'element-plus'
3
+ import zhCn from 'element-plus/es/locale/lang/zh-cn'
4
+ import App from './App.vue'
5
+ import Root from './Root.vue'
6
+ import Login from './Login.vue'
7
+ import Home from './Home.vue'
8
+ import { createHttp } from '../core/http.js'
9
+ import { createRegistry } from '../core/registry.js'
10
+ import { createAuth } from '../core/auth.js'
11
+ import { createViewsConfigLoader } from '../core/views.js'
12
+ import { createRelationViewLoader } from '../core/views.js'
13
+ import { createDrawerViewLoader } from '../composables/drawer.js'
14
+ import { createDjango } from '../composables/context.js'
15
+ import { createDjangoRouter, genModelRouters } from '../router/index.js'
16
+
17
+ export function createDjangoApp(options = {}) {
18
+ const apps = options.apps ?? {}
19
+ const viewModules = options.viewModules ?? {}
20
+ const registry =
21
+ options.registry ??
22
+ createRegistry({
23
+ apps,
24
+ http: options.http ?? createHttp({ baseURL: options.apiBaseURL ?? '/api/' }),
25
+ loadViewsConfig:
26
+ options.loadViewsConfig ?? createViewsConfigLoader(options.configModules ?? {}),
27
+ })
28
+ const auth =
29
+ options.auth === false
30
+ ? undefined
31
+ : options.auth && typeof options.auth === 'object'
32
+ ? options.auth
33
+ : createAuth({ ...options.authOptions, http: registry.http })
34
+ const modelRoutes = genModelRouters(
35
+ apps,
36
+ options.modelViews ?? { modules: viewModules, templates: options.templates },
37
+ )
38
+ const homePath = options.homePath ?? '/home/'
39
+ const loginPath = options.loginPath ?? '/auth/login/'
40
+ if (homePath === '/' || homePath === loginPath) throw new Error('homePath 不能指向根路径或登录页')
41
+ const application = {
42
+ title: options.title ?? 'vue3-django',
43
+ homePath,
44
+ loginPath,
45
+ menus: options.menus,
46
+ layoutProps: {
47
+ loadDrawerView: createDrawerViewLoader(viewModules),
48
+ ...options.layoutProps,
49
+ },
50
+ }
51
+ const router =
52
+ options.router ??
53
+ createDjangoRouter({
54
+ auth,
55
+ history: options.history,
56
+ loginPath,
57
+ routes: [
58
+ {
59
+ path: '/',
60
+ component: options.components?.layout ?? Root,
61
+ children: [
62
+ { path: '', redirect: homePath },
63
+ {
64
+ path: '/home/',
65
+ alias: '/welcome/',
66
+ name: 'django-home',
67
+ component: options.components?.home ?? Home,
68
+ meta: { title: '欢迎', icon: 'home' },
69
+ },
70
+ ...modelRoutes,
71
+ ...(options.routes ?? []),
72
+ ],
73
+ },
74
+ auth
75
+ ? {
76
+ path: loginPath,
77
+ component: options.components?.login ?? Login,
78
+ meta: { loginRequired: false, layout: 'main' },
79
+ }
80
+ : { path: loginPath, redirect: homePath },
81
+ { path: '/:pathMatch(.*)*', redirect: homePath },
82
+ ],
83
+ })
84
+ const context = {
85
+ ...options.context,
86
+ apps,
87
+ auth,
88
+ application,
89
+ revisions: options.context?.revisions ?? reactive({}),
90
+ loadRelationView: options.context?.loadRelationView ?? createRelationViewLoader(viewModules),
91
+ }
92
+ const app = createApp({
93
+ render: () =>
94
+ h(
95
+ ElConfigProvider,
96
+ { locale: options.locale ?? zhCn },
97
+ { default: () => h(options.components?.app ?? App) },
98
+ ),
99
+ })
100
+ app.use(createDjango({ registry, ...context })).use(router)
101
+ return { app, router, registry, auth, mount: (target = '#app') => app.mount(target) }
102
+ }
package/src/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  import './style.css'
2
+ export { createDjangoApp } from './app/index.js'
3
+ export { default as DjangoApp } from './app/App.vue'
4
+ export { default as DjangoRoot } from './app/Root.vue'
5
+ export { default as DjangoLogin } from './app/Login.vue'
6
+ export { default as DjangoHome } from './app/Home.vue'
2
7
  export { createHttp, DrfError, joinErrors } from './core/http.js'
3
8
  export { AppModel, Register, createRegistry } from './core/registry.js'
4
9
  export {
@@ -10,7 +15,12 @@ export {
10
15
  } from './core/metadata.js'
11
16
  export { createDjango, useDjango } from './composables/context.js'
12
17
  export { createAuth } from './core/auth.js'
13
- export { createDjangoRouter, genModelRouters, safeRedirect } from './router/index.js'
18
+ export {
19
+ createDjangoRouter,
20
+ genModelRouters,
21
+ import_or_use_template,
22
+ safeRedirect,
23
+ } from './router/index.js'
14
24
  export { default as ModelForm } from './components/model/Form.vue'
15
25
  export { default as ModelTable } from './components/model/Table.vue'
16
26
  export { default as ModelListView } from './views/model/list.vue'
@@ -1,6 +1,24 @@
1
1
  import { createRouter, createWebHashHistory } from 'vue-router'
2
- import ModelListView from '../views/model/list.vue'
3
- import ModelEditView from '../views/model/edit.vue'
2
+
3
+ const modelTemplates = import.meta.glob('../views/model/*.vue')
4
+
5
+ // Vite must discover host views at build time; pass the host's import.meta.glob map.
6
+ export function import_or_use_template(path, template, modules = {}, templates = {}) {
7
+ if (!/^[\w-]+(?:\/[\w-]+)*$/.test(path) || !/^[\w-]+$/.test(template)) {
8
+ throw new Error('模型视图路径无效')
9
+ }
10
+ const suffix = `/views/${path}.vue`
11
+ const matches = Object.entries(modules).filter(([key]) => key.endsWith(suffix))
12
+ if (matches.length > 1) throw new Error(`模型视图 ${path} 重复`)
13
+ return async () => {
14
+ const loader =
15
+ matches[0]?.[1] ?? templates[template] ?? modelTemplates[`../views/model/${template}.vue`]
16
+ if (!loader) throw new Error(`模型视图 ${path} 与模板 ${template} 均未找到`)
17
+ // An existing view's runtime/import error must not be swallowed by a fallback.
18
+ const module = typeof loader === 'function' ? await loader() : loader
19
+ return module.default ?? module
20
+ }
21
+ }
4
22
 
5
23
  export function safeRedirect(value, fallback = '/') {
6
24
  return typeof value === 'string' &&
@@ -40,18 +58,14 @@ export function createDjangoRouter({
40
58
  return router
41
59
  }
42
60
 
43
- export function genModelRouters(
44
- apps,
45
- components = {
46
- list: ModelListView,
47
- create: ModelEditView,
48
- edit: ModelEditView,
49
- },
50
- ) {
61
+ export function genModelRouters(apps, components) {
62
+ const options = components?.modules || components?.templates ? components : {}
51
63
  const views =
52
- typeof components === 'object' && components.list
53
- ? components
54
- : { list: components, create: components, edit: components }
64
+ options === components || !components
65
+ ? {}
66
+ : typeof components === 'object' && components.list
67
+ ? components
68
+ : { list: components, create: components, edit: components }
55
69
  return Object.entries(apps).flatMap(([app, definition]) =>
56
70
  definition.hidden === true || definition.hidden === 'true'
57
71
  ? []
@@ -59,25 +73,33 @@ export function genModelRouters(
59
73
  const path = `/${app}/${name}/`,
60
74
  appModel = `${app}.${name}`,
61
75
  title = model.verbose_name ?? name
76
+ const resolveView = (view, template = view) =>
77
+ views[view] ??
78
+ import_or_use_template(
79
+ `${app}/${name}/${view}`,
80
+ template,
81
+ options.modules,
82
+ options.templates,
83
+ )
62
84
  return [
63
85
  {
64
86
  path,
65
87
  name: `${app}-${name}-list`,
66
- component: views.list,
88
+ component: resolveView('list'),
67
89
  props: { appModel, mode: 'list' },
68
90
  meta: { title: `${title}列表`, model },
69
91
  },
70
92
  {
71
93
  path: `${path}add/`,
72
94
  name: `${app}-${name}-add`,
73
- component: views.create ?? views.edit,
95
+ component: views.create ?? views.edit ?? resolveView('edit'),
74
96
  props: { appModel, mode: 'create' },
75
97
  meta: { title: `新增${title}`, model },
76
98
  },
77
99
  {
78
100
  path: `${path}:id/`,
79
101
  name: `${app}-${name}-edit`,
80
- component: views.edit,
102
+ component: resolveView('edit'),
81
103
  props: (route) => ({ appModel, mode: 'edit', id: route.params.id }),
82
104
  meta: { title: `编辑${title}`, model },
83
105
  },
@@ -82,6 +82,7 @@ defineExpose({ submit: () => form.value?.submit(), load: () => form.value?.load(
82
82
  />
83
83
  <ModelForm
84
84
  v-else
85
+ class="vd-model-page"
85
86
  ref="form"
86
87
  v-model="data"
87
88
  v-bind="$attrs"
@@ -55,6 +55,7 @@ defineExpose({ refresh: () => table.value?.refresh() })
55
55
  :closable="false"
56
56
  />
57
57
  <component
58
+ class="vd-model-page"
58
59
  :is="config.mode === 'grid' && gridComponent ? gridComponent : ModelTable"
59
60
  v-else-if="config"
60
61
  ref="table"