Owl 组件

Odoo JavaScript 框架使用一个名为 Owl 的自定义组件框架。它是一个声明式组件系统,设计上大致借鉴了 Vue 和 React。组件使用 QWeb 模板 定义,并加入一些 Owl 特有的指令。官方 Owl 文档 包含完整的参考手册和教程。

Important

尽管代码位于 web 模块中,但它是在一个独立的 GitHub 仓库中维护的。因此,对 Owl 的任何修改都应通过 https://github.com/odoo/owl 上的拉取请求(pull request)进行。

Note

目前,所有 Odoo 版本(从版本 14 开始)都使用相同的 Owl 版本。

使用 Owl 组件

Owl documentation 已详细介绍了 Owl 框架,因此本页仅提供 Odoo 特有的信息。但首先,让我们看看如何在 Odoo 中创建一个简单的组件。

const { useState } = owl.hooks;
const { xml } = owl.tags;

class MyComponent extends Component {
    setup() {
        this.state = useState({ value: 1 });
    }

    increment() {
        this.state.value++;
    }
}
MyComponent.template = xml
    `<div t-on-click="increment">
        <t t-esc="state.value">
    </div>`;

该示例表明,Owl 作为一个名为 owl 的库在全局命名空间中可用:可以像 Odoo 中的大多数库一样直接使用它。注意,这里我们将模板定义为静态属性,但没有使用 static 关键字,因为某些浏览器不支持该关键字(Odoo JavaScript 代码应符合 Ecmascript 2019 规范)。

这里我们借助 xml 辅助函数在 JavaScript 代码中定义模板。但这只适合入门。在实践中,Odoo 的模板应定义在 xml 文件中,以便进行翻译。在这种情况下,组件只需定义模板名称即可。

在实践中,大多数组件应定义 2 到 3 个文件,且位于同一位置:一个 JavaScript 文件(my_component.js)、一个模板文件(my_component.xml),以及可选的 scss(或 css)文件(my_component.scss)。然后应将这些文件添加到某个资源包(assets bundle)中。Web 框架会负责加载 javascript/css 文件,并将模板加载到 Owl 中。

上述组件应按如下方式定义:

const { useState } = owl.hooks;

class MyComponent extends Component {
    ...
}
MyComponent.template = 'myaddon.MyComponent';

模板现在位于对应的 xml 文件中:

<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">

<t t-name="myaddon.MyComponent" owl="1">
  <div t-on-click="increment">
    <t t-esc="state.value"/>
  </div>
</t>

</templates>

Odoo 代码尚未完全用 Owl 编写,因此需要一种方法来区分 Owl 模板(新代码)与旧模板(用于组件)。为了以向后兼容的方式实现这一点,所有新模板都应将 owl 属性设置为 1。

Note

别忘了在您的 Owl 模板中设置 owl="1"!

Note

模板名称应遵循 addon_name.ComponentName 命名约定。

更多内容

最佳实践

首先,组件是类,因此它们有构造函数。但构造函数在 JavaScript 中是一种特殊方法,无法以任何方式重写。由于这在 Odoo 中偶尔是有用的模式,我们需要确保 Odoo 中没有任何组件直接使用 constructor 方法,而应使用 setup 方法:

// correct:
class MyComponent extends Component {
    setup() {
        // initialize component here
    }
}

// incorrect. Do not do that!
class IncorrectComponent extends Component {
    constructor(parent, props) {
        // initialize component here
    }
}

另一个良好实践是为模板名称使用一致的命名约定:addon_name.ComponentName。这可以避免 Odoo 插件之间的名称冲突。

参考列表

Odoo web 客户端使用 Owl 组件构建。为了方便使用,Odoo JavaScript 框架提供了一套通用组件,可在一些常见场景中复用,例如下拉框、复选框或日期选择器。本页介绍如何使用这些通用组件。

技术名称

简介

ActionSwiper

一个滑动组件,用于在触摸滑动时执行操作

CheckBox

一个简单的复选框组件,旁边带有标签

ColorList

可供选择的颜色列表

Dropdown

功能齐全的下拉菜单

Notebook

使用选项卡在页面之间导航的组件

Pager

用于处理分页的小组件

ActionSwiper

位置

@web/core/action_swiper/action_swiper

说明

这是一个当元素被水平滑动时可以执行操作的组件。swiper 会包裹一个目标元素并为其添加操作。当用户滑动超过其宽度的指定比例并松开时,操作就会被执行。

<ActionSwiper onLeftSwipe="Object" onRightSwipe="Object">
  <SomeElement/>
</ActionSwiper>

如上所示,使用该组件最简单的方式是在 xml 模板中直接将它包裹在目标元素外面。但有时,您可能想扩展现有元素而不想复制模板。这完全可以做到。

如果想扩展现有元素的行为,必须通过直接包裹的方式将该元素放在其中。此外,还可以有条件地添加 props,以控制元素何时可以滑动、其动画以及执行操作所需滑动的最小比例。

您可以使用该组件轻松地与记录、消息、列表项等进行交互。

ActionSwiper 使用示例

以下示例创建了一个基本的 ActionSwiper 组件。这里,双向滑动均已启用。

<ActionSwiper
  onRightSwipe="
    {
      action: '() => Delete item',
      icon: 'fa-delete',
      bgColor: 'bg-danger',
    }"
  onLeftSwipe="
    {
      action: '() => Star item',
      icon: 'fa-star',
      bgColor: 'bg-warning',
    }"
>
  <div>
    Swipable item
  </div>
</ActionSwiper>

Note

在使用从右到左(RTL)语言时,操作会对调。

Props(属性)

名称

类型

说明

animationOnMove

Boolean

可选布尔值,用于确定滑动过程中是否带有位移效果

animationType

String

可选动画,在滑动结束后使用(bounce 或 forwards)

onLeftSwipe

Object

如果提供,actionswiper 可以向左滑动

onRightSwipe

Object

如果提供,actionswiper 可以向右滑动

swipeDistanceRatio

数字

可选的最小宽度比例,必须滑动超过该比例才会执行操作

您可以同时使用 onLeftSwipe 和 onRightSwipe 这两个 props。

用于左/右滑动的 Object 必须包含:

  • action,即可作为回调使用的 Function。一旦在给定方向完成滑动,就会执行该操作。

  • icon 是要使用的图标类,通常用于表示该操作。必须为 string。

  • bgColor 是用于装饰操作的背景颜色。可以是以下 bootstrap 情境色 之一(danger、info、secondary、success 或 warning)。

必须提供这些值,以定义 swiper 的行为和外观。

示例:扩展现有组件

在下面的示例中,可以使用 xpath 将现有元素包裹在 ActionSwiper 组件中。这里,添加了一个 swiper,用于在 mail 中将消息标记为已读。

<xpath expr="//*[hasclass('o_Message')]" position="after">
  <ActionSwiper
    onRightSwipe="messaging.device.isMobile and messageView.message.isNeedaction ?
      {
        action: () => messageView.message.markAsRead(),
        icon: 'fa-check-circle',
        bgColor: 'bg-success',
      } : undefined"
  />
</xpath>
<xpath expr="//ActionSwiper" position="inside">
  <xpath expr="//*[hasclass('o_Message')]" position="move"/>
</xpath>

CheckBox

位置

@web/core/checkbox/checkbox

说明

这是一个简单的复选框组件,旁边带有标签。复选框与标签相互关联:点击标签时,复选框的状态会切换。

<CheckBox value="boolean" disabled="boolean" t-on-change="onValueChange">
  Some Text
</CheckBox>

Props(属性)

名称

类型

说明

value

boolean

如果为 true,复选框被勾选,否则为未勾选

disabled

boolean

如果为 true,复选框被禁用,否则为启用状态

ColorList

位置

@web/core/colorlist/colorlist

说明

ColorList 允许您从预定义的列表中选择一种颜色。默认情况下,该组件显示当前选中的颜色,并且在提供 canToggle props 之前不可展开。不同的 props 可以改变其行为:让列表始终展开,或让它在点击后作为切换器,显示可用颜色列表直到做出选择。

Props(属性)

名称

类型

说明

canToggle

boolean

可选。colorlist 是否可以在点击时展开列表

colors

array

要在组件中显示的颜色列表。每种颜色都有一个唯一的 id

forceExpanded

boolean

可选。如果为 true,列表始终展开

isExpanded

boolean

可选。如果为 true,列表默认展开

onColorSelected

function

选择颜色后执行的回调

selectedColor

number

可选。所选颜色的 id

颜色 id 如下:

编号

颜色

0

无颜色

1

红色

2

橙色

3

黄色

4

浅蓝色

5

深紫色

6

鲑鱼粉

7

中蓝色

8

深蓝色

9

洋红色

12

绿色

11

紫色

位置

@web/core/dropdown/dropdown 与 @web/core/dropdown/dropdown_item

说明

下拉菜单是出奇复杂的组件。它们需要提供许多功能,例如:

  • 点击时切换项目列表的显示

  • 同级相邻下拉菜单:当其中一个打开时,悬停即可切换其他菜单

  • 点击外部时关闭

  • 可选择在选择项目时关闭项目列表

  • 选择项目时调用一个函数

  • 支持任意层级的子下拉菜单

  • SIY:样式由您自己定制

  • 可配置的热键,用于打开/关闭下拉菜单或选择下拉项目

  • 键盘导航(方向键、tab、shift+tab、home、end、enter 和 escape)

  • 在页面滚动或调整大小时自动重新定位

  • 智能选择打开方向(自动处理从右到左方向)。

为了一劳永逸地解决这些问题,Odoo 框架提供了两个组件:Dropdown 组件(即下拉菜单本身),以及用于项目列表中每个元素的 DropdownItem。

<Dropdown>
  <t t-set-slot="toggler">
    <!-- "toggler" slot content is rendered inside a button -->
    Click me to toggle the dropdown menu !
  </t>
  <!-- "default" slot content is rendered inside a div -->
  <DropdownItem onSelected="selectItem1">Menu Item 1</DropdownItem>
  <DropdownItem onSelected="selectItem2">Menu Item 2</DropdownItem>
</Dropdown>

Props(属性)

一个 <Dropdown/> 组件本质上就是一个 <div class="dropdown"/>,其旁边有一个 <button class="dropdown-toggle"/>,紧邻菜单 div (<div class="dropdown-menu"/>)。该按钮决定菜单是否存在于 DOM 中。

Dropdown

类型

说明

startOpen

布尔值

下拉菜单的初始打开状态(默认为 false)

menuClass

string

应用于下拉菜单 <div class="dropdown-menu"/> 的额外 css 类

togglerClass

string

应用于切换器 <button class="dropdown-toggle"/> 的额外 css 类

hotkey

string

通过键盘切换打开状态的热键

tooltip

string

在切换器上添加工具提示

beforeOpen

函数

在打开之前执行逻辑的钩子。可以是异步的。

manualOnly

布尔值

如果为 true,则仅在点击按钮时切换下拉菜单(默认为 false)

title

string

用于 <button class="dropdown-toggle"/> 的 title 属性内容(默认:无)

position

string

定义所需的菜单打开位置。会自动应用 RTL 方向。应为有效的 usePosition 钩子位置。(默认:bottom-start)

toggler

"parent" 或 undefined

当设置为 "parent" 时,<button class="dropdown-toggle"/> 不会被渲染(因此忽略 toggler 插槽),切换功能改由父节点处理(例如用例:数据透视单元格)。(默认:undefined)

一个 <DropdownItem/> 本质上就是一个 span (<span class="dropdown-item"/>)。选中某个 <DropdownItem/> 时,它会调用自己的 onSelected prop。如果该 prop 是方法,且方法需要使用 this 值,请确保对其进行绑定。

DropdownItem

类型

说明

onSelected

函数

下拉菜单项被选中时调用的函数。

parentClosingMode

none | closest | all

选中该项时,控制关闭哪个父级下拉菜单:none、closest 或 all (默认 = all)

hotkey

string

可选,用于选择该项目的热键

href

string

如果提供,DropdownItem 将变为 <a href="value" class="dropdown-item"/>,而不是 <span class="dropdown-item"/>。(默认:不提供)

title

string

可选的 title 属性,将传递给 DropdownItem 的根节点。(默认:不提供)

dataset

对象

可选对象,包含应添加到根元素 dataset 中的值。这能让该元素更容易以编程方式查找,例如在测试或导览(tour)中。

技术说明

渲染出的 DOM 结构如下:

<div class="dropdown">
    <button class="dropdown-toggle">Click me !</button>
    <!-- following <div/> will or won't appear in the DOM depending on the state controlled by the preceding button -->
    <div class="dropdown-menu">
        <span class="dropdown-item">Menu Item 1</span>
        <span class="dropdown-item">Menu Item 2</span>
    </div>
</div>

要正确使用 <Dropdown/> 组件,需要填充两个 OWL 插槽:

  • toggler 插槽:它包含您的下拉菜单的 切换 元素,渲染在下拉菜单的 button 内部(除非将 toggler prop 设置为 parent),

  • default 插槽:它包含下拉菜单本身的 元素,渲染在 <div class="dropdown-menu"/> 内部。虽然并非必需,但 menu 插槽中通常至少有一个 DropdownItem。

当多个下拉菜单在 DOM 中共享同一个父元素时,它们被视为同一个组的成员,并会相互通知各自的状态变化。这意味着当其中一个下拉菜单处于打开状态时,其他下拉菜单会在鼠标悬停时自动打开,无需点击。

示例:直接同级下拉菜单

当点击 File 、Edit 或 About 中某个下拉菜单的切换器时,其他下拉菜单会在鼠标悬停时自动打开。

<div>
  <Dropdown>
    <t t-set-slot="toggler">File</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-open')">Open</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-document')">New Document</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-spreadsheet')">New Spreadsheet</DropdownItem>
  </Dropdown>
  <Dropdown>
    <t t-set-slot="toggler">Edit</t>
    <DropdownItem onSelected="() => this.onItemSelected('edit-undo')">Undo</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('edit-redo')">Redo</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('edit-find')">Search</DropdownItem>
  </Dropdown>
  <Dropdown>
    <t t-set-slot="toggler">About</t>
    <DropdownItem onSelected="() => this.onItemSelected('about-help')">Help</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('about-update')">Check update</DropdownItem>
  </Dropdown>
</div>

示例:使用 t-call 的多级下拉菜单

本示例展示如何制作一个 File 下拉菜单,并为 New 和 Save as... 子元素设置子菜单。

<t t-name="addon.Dropdown.File" owl="1">
  <Dropdown>
    <t t-set-slot="toggler">File</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-open')">Open</DropdownItem>
    <t t-call="addon.Dropdown.File.New"/>
    <DropdownItem onSelected="() => this.onItemSelected('file-save')">Save</DropdownItem>
    <t t-call="addon.Dropdown.File.Save.As"/>
  </Dropdown>
</t>

<t t-name="addon.Dropdown.File.New" owl="1">
  <Dropdown>
    <t t-set-slot="toggler">New</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-document')">Document</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-spreadsheet')">Spreadsheet</DropdownItem>
  </Dropdown>
</t>

<t t-name="addon.Dropdown.File.Save.As" owl="1">
  <Dropdown>
    <t t-set-slot="toggler">Save as...</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-save-as-csv')">CSV</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-save-as-pdf')">PDF</DropdownItem>
  </Dropdown>
</t>

示例:多级下拉菜单(嵌套)

<Dropdown>
  <t t-set-slot="toggler">File</t>
  <DropdownItem onSelected="() => this.onItemSelected('file-open')">Open</DropdownItem>
  <Dropdown>
    <t t-set-slot="toggler">New</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-document')">Document</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-new-spreadsheet')">Spreadsheet</DropdownItem>
  </Dropdown>
  <DropdownItem onSelected="() => this.onItemSelected('file-save')">Save</DropdownItem>
  <Dropdown>
    <t t-set-slot="toggler">Save as...</t>
    <DropdownItem onSelected="() => this.onItemSelected('file-save-as-csv')">CSV</DropdownItem>
    <DropdownItem onSelected="() => this.onItemSelected('file-save-as-pdf')">PDF</DropdownItem>
  </Dropdown>
</Dropdown>

示例:递归多级下拉菜单

在此示例中,我们递归调用一个模板来显示树状结构。

<t t-name="addon.MainTemplate" owl="1">
  <div>
    <t t-call="addon.RecursiveDropdown">
      <t t-set="name" t-value="'Main Menu'" />
      <t t-set="items" t-value="state.menuItems" />
    </t>
  </div>
</t>

<t t-name="addon.RecursiveDropdown" owl="1">
  <Dropdown>
    <t t-set-slot="toggler"><t t-esc="name"/></t>
      <t t-foreach="items" t-as="item" t-key="item.id">

        <!-- If this item has no child: make it a <DropdownItem/> -->
        <t t-if="!item.childrenTree.length">
          <DropdownItem onSelected="() => this.onItemSelected(item)" t-esc="item.name"/>
        </t>
        <!-- Else: recursively call the current dropdown template. -->
        <t t-else="" t-call="addon.RecursiveDropdown">
          <t t-set="name" t-value="item.name" />
          <t t-set="items" t-value="item.childrenTree" />
        </t>

      </t>
    </t>
  </Dropdown>
</t>

Notebook

位置

@web/core/notebook/notebook

说明

Notebook 用于在选项卡式界面中显示多个页面。选项卡可以位于元素顶部以水平显示,也可以位于左侧以垂直布局显示。

有两种方式定义要实例化的 Notebook 页面:使用 slot,或传递专用的 props。

Props(属性)

名称

类型

说明

anchors

object

可选。允许锚点导航到不可见选项卡内的元素。

className

string

可选。设置在组件根元素上的 classname。

defaultPage

string

可选。默认显示的页面 id。

orientation

string

可选。选项卡方向是 horizontal 还是 vertical。

onPageUpdate

function

可选。页面更改后执行的回调函数。

pages

array

可选。包含从模板填充的 page 列表。

Example

第一种方式是在组件的插槽中设置页面。

<Notebook orientation="'vertical'">
  <t t-set-slot="page_1" title="'Page 1'" isVisible="true">
    <h1>My First Page</h1>
    <p>It's time to build Owl components. Did you read the documentation?</p>
  </t>
  <t t-set-slot="page_2" title="'2nd page'" isVisible="true">
    <p>Wise owl's silent flight. Through the moonlit forest deep, guides my path to code</p>
  </t>
</Notebook>

另一种定义页面的方式是传递属性。如果某些页面共享相同的结构,这会很有用。首先为您可能使用的每个页面模板创建一个组件。

import { Notebook } from "@web/core/notebook/notebook";

class MyTemplateComponent extends owl.Component {
  static template = owl.tags.xml`
    <h1 t-esc="props.title" />
    <p t-esc="props.text" />
  `;
}

class MyComponent extends owl.Component {
  get pages() {
    return [
      {
        Component: MyTemplateComponent,
        title: "Page 1",
        props: {
          title: "My First Page",
          text: "This page is not visible",
        },
      },
      {
        Component: MyTemplateComponent,
        id: "page_2",
        title: "Page 2",
        props: {
          title: "My second page",
          text: "You're at the right place!",
        },
      },
    ]
  }
}
MyComponent.template = owl.tags.xml`
  <Notebook defaultPage="'page_2'" pages="pages" />
`;

此处展示了这两个示例:

垂直和水平布局示例

Pager

位置

@web/core/pager/pager

说明

Pager 是一个处理分页的小组件。页面由 offset 和 limit (页面大小)定义。它显示当前页面和元素 total 总数,例如 “9-12 / 20”。在前面的示例中,offset 为 8,limit 为 4,total 为 20。它有两个按钮(”Previous” 和 “Next”)用于在页面之间导航。

Note

Pager 可以在任何地方使用,但主要用于控制面板中。参见 usePager 钩子以操作控制面板的分页器。

<Pager offset="0" limit="80" total="50" onUpdate="doSomething" />

Props(属性)

名称

类型

说明

offset

number

页面第一个元素的索引。从 0 开始,但分页器显示 offset + 1。

limit

number

页面大小。offset 与 limit 之和对应页面最后一个元素的索引。

total

number

页面可到达的元素总数。

onUpdate

function

页面被分页器修改时调用的函数。该函数可以是异步的,在其执行期间分页器不可编辑。

isEditable

boolean

允许点击当前页面进行编辑(默认为 true)。

withAccessKey

boolean

为上一页按钮绑定快捷键 p,为下一页按钮绑定 n (默认为 true)。