在Desk页面中使用Vue

使用 Vue 为你的 Desk 应用添加页面,可以让你兼得两者的便利:

  1. 你可以使用 Vue 的响应式和组合式特性
  2. 你可以使用 Frappe JS API

这一切无需手动配置 Vue 应用即可实现。你可以按照
以下步骤进行设置。

创建一个页面

导航到 Page DocType(位于 /app/page),然后创建一个新的 Page 条目。
系统会在你选择的模块中为你的页面创建新文件。

检查创建的文件

在你应用目录下的模块文件夹中,你会找到一个新文件夹,里面包含三个
文件:

└── app
    └── app
        └── module
            └── page
                └── test_vue
                    ├── __init__.py
                    ├── test_vue.json
                    └── test_vue.js

其中,在新创建的 JavaScript 文件中,你会看到 make_app_page 被调用:

frappe.pages['test-vue'].on_page_load = function (wrapper) {
  var page = frappe.ui.make_app_page({
    parent: wrapper,
    title: 'None',
    single_column: true,
  });
};

这用于创建一个新页面。更多信息请参阅 Page API。

当你访问 /app/test-vue 时,这个文件会被加载,你可以访问该
路径,届时会显示一个标题为“None”的空页面。

创建 Vue 文件

要使用 Vue,你的 .vue 源文件需要被转译和打包。Frappe
框架开箱即用,已内置此功能。

我们现在将创建两个文件:一个 .vue 文件,以及一个用于加载你的 Vue
代码的 .js 文件。你可以将这些文件添加到应用的 public/js 文件夹下:

└── app
    └── app
        └── public
            └── test_vue
                ├── TestVue.vue
                └── test_vue.bundle.js

首先,我们将创建 .vue 文件 TestVue.vue。这是一些用于测试设置的简单 Vue 代码:

<script setup>
import { ref } from 'vue';

const message = ref('Hello, World');
</script>
<template>

<h1>{{ message }}</h1>
</template>

其次,创建用于加载 Vue 代码的 .js 文件:

import { createApp } from 'vue';
import TestVue from './TestVue.vue';

// A simple function to mount your Vue app
function setup_vue(wrapper) {
  const app = createApp(TestVue);
  app.mount(wrapper.get(0));
  return app;
}

// We'll call this function from the generated test_vue.js file
frappe.ui.setup_vue = setup_vue;
export default setup_vue;

引入打包文件

在生成的 test_vue.js 文件中,添加以下代码以加载 Vue 应用:

frappe.pages['test-vue'].on_page_load = function (wrapper) {
  const page = frappe.ui.make_app_page({
    parent: wrapper,
    title: 'Test Vue',
    single_column: true,
  });

  // hot reload when in developer mode
  if (frappe.boot.developer_mode) {
    frappe.hot_update ??= frappe.hot_update;
    frappe.hot_update.push(() => load_vue(wrapper));
  }
};
frappe.pages['test-vue'].on_page_show = (wrapper) => load_vue(wrapper);

// Simple callback function to load Vue in the page
async function load_vue(wrapper) {
  const $parent = $(wrapper).find('.layout-main-section');
  $parent.empty();

  // Require the bundle and mount the Vue app
  await frappe.require('test_vue.bundle.js');
  frappe.test_vue_app = frappe.ui.setup_vue($parent);
}

这会调用 load_vue 函数,该函数会 requires 打包文件,并在页面加载或显示时挂载
Vue 应用。

构建或运行开发服务器

要构建你的代码,你可以调用:

bench build

注意:这会为你 bench 上的所有应用构建前端代码。

要运行开发服务器,你可以导航到 frappe 应用(即 bench/apps/frappe)的文件夹并运行:

npm run build -- --apps app --watch

这会监听你应用中的任何更改并重新构建代码,这应该会
在你的浏览器中触发热重载。

如果你一切操作正确,你应该会看到你的页面显示 Vue 应用的消息: